Author Topic: Program doesn't print variable value as expected  (Read 2396 times)

0 Members and 1 Guest are viewing this topic.

Offline Dadu@Topic starter

  • Contributor
  • Posts: 34
  • Country: in
Program doesn't print variable value as expected
« on: February 22, 2022, 03:35:14 pm »
When I compile code it doesn't print value as expected

Code: [Select]
#include<stdio.h>
#include<stdlib.h>

int main()
{
   int x = 1;
   int y = x++;
   
   printf("x : %d\n", x);
   printf("y : %d\n", y);
 
   return 0;
}

x : 2
y : 1

I was expecting 1 should print for variable x.  when I researched about it, I found that  I need to understand difference between pre and post increment oprator.  I tried to figure it out but it's going off the top of my head


 

Offline IanB

  • Super Contributor
  • ***
  • Posts: 11885
  • Country: us
Re: Program doesn't print variable value as expected
« Reply #1 on: February 22, 2022, 03:41:02 pm »
I was expecting 1 should print for variable x.  when I researched about it, I found that  I need to understand difference between pre and post increment oprator.  I tried to figure it out but it's going off the top of my head

You should expect 2 for x.

If you write "x++" it means "x = x + 1". "x++" changes the value of x.

This is not about the difference between pre- and post- increment. The important part here is "increment", i.e. "add 1 to". If x is 1 and you increment it, it becomes 2.

In other words, what your code does is this:
Code: [Select]
    int x = 1;
    int y = x; x = x + 1;  // same as y = x++;
« Last Edit: February 22, 2022, 03:45:00 pm by IanB »
 
The following users thanked this post: Dadu@

Offline Bassman59

  • Super Contributor
  • ***
  • Posts: 2501
  • Country: us
  • Yes, I do this for a living
Re: Program doesn't print variable value as expected
« Reply #2 on: February 22, 2022, 04:48:56 pm »
When I compile code it doesn't print value as expected

Code: [Select]
#include<stdio.h>
#include<stdlib.h>

int main()
{
   int x = 1;
   int y = x++;
   
   printf("x : %d\n", x);
   printf("y : %d\n", y);
 
   return 0;
}

x : 2
y : 1

I was expecting 1 should print for variable x.  when I researched about it, I found that  I need to understand difference between pre and post increment oprator.  I tried to figure it out but it's going off the top of my head

The output is correct.

You incremented x before you printed it.
 

Offline free_electron

  • Super Contributor
  • ***
  • Posts: 8517
  • Country: us
    • SiliconValleyGarage
Re: Program doesn't print variable value as expected
« Reply #3 on: February 22, 2022, 05:17:35 pm »
what does this produce :

y = (x++);

i never liked code like this.
To me, both x and y should be identical
i read this as 'set y to the result of x++' unwrapped further : increment x. assign result to y"

x = x + 1; 
y = x;

constructions like this make it difficult for non-coders to understand what exactly is going on. You need to know too many little details.
Professional Electron Wrangler.
Any comments, or points of view expressed, are my own and not endorsed , induced or compensated by my employer(s).
 
The following users thanked this post: nctnico

Offline Siwastaja

  • Super Contributor
  • ***
  • Posts: 8172
  • Country: fi
Re: Program doesn't print variable value as expected
« Reply #4 on: February 22, 2022, 05:31:00 pm »
To me, both x and y should be identical

I'm glad you haven't designed the C language.

Pre- and post-incrementation operands are some of the easiest to learn.

In more complex examples, concept of sequence points needs to be learnt. In your simple example - irrelevant. Adding extra parenthesis - irrelevant, as it should be. Your idea that parenthesis should change the meaning, is just pure horror.

x++ increments x, and returns the old value of x. It's totally beyond me why adding extra parenthesis should change the meaning of x++.
« Last Edit: February 22, 2022, 05:33:59 pm by Siwastaja »
 
The following users thanked this post: newbrain, emece67

Offline SiliconWizard

  • Super Contributor
  • ***
  • Posts: 14466
  • Country: fr
Re: Program doesn't print variable value as expected
« Reply #5 on: February 22, 2022, 06:21:56 pm »
So this forum is turning into a free course? One question is fine, but a series of them in a row that are all very basic, I call that a free course.

 

Offline DavidAlfa

  • Super Contributor
  • ***
  • Posts: 5904
  • Country: es
Re: Program doesn't print variable value as expected
« Reply #6 on: February 22, 2022, 06:36:07 pm »
That's fine, that's why forums exist.
Nobody is forcing you to answer!
Or maybe yes? Is someone pointing you with a gun?  :-DD
Hantek DSO2x1x            Drive        FAQ          DON'T BUY HANTEK! (Aka HALF-MADE)
Stm32 Soldering FW      Forum      Github      Donate
 

Offline SiliconWizard

  • Super Contributor
  • ***
  • Posts: 14466
  • Country: fr
Re: Program doesn't print variable value as expected
« Reply #7 on: February 22, 2022, 06:44:25 pm »
I find that an abusive use of a forum. A forum's purpose is not to mitigate people's laziness to even open a book. But I'll let Dave be judge of that - it's his forum, not mine. Even if he doesn't care about that, the questions here don't have anything to do with microcontrollers specifically, so it's just polluting the section. Just my 2 cents.

As to the question, just opening a book on C would answer this in a jiffy. As I and a few others note on a regular basis, it's amazing how so many people insist on using C without caring to learn it, and just want to figure it out as they go. And universities which increasingly do not teach it either, yet ask students to use it. It's mind-boggling, and an overall concerning issue, but hey. Let's drown together, it's more fun. =)
« Last Edit: February 22, 2022, 06:59:58 pm by SiliconWizard »
 

Offline TomS_

  • Frequent Contributor
  • **
  • Posts: 834
  • Country: gb
Re: Program doesn't print variable value as expected
« Reply #8 on: February 22, 2022, 08:46:11 pm »
I find that an abusive use of a forum. A forum's purpose is not to mitigate people's laziness to even open a book. But I'll let Dave be judge of that - it's his forum, not mine. Even if he doesn't care about that, the questions here don't have anything to do with microcontrollers specifically, so it's just polluting the section. Just my 2 cents.

Perhaps use the "report to moderator" link that is in the bottom right of every post, if you feel it should go into some other section (theres a dedicated programming section for example)?

But I'd agree that this is not microcontroller specific (none of the other questions the OP has posted in this forum seem to be either), so it should probably be moved to the programming forum.
 

Offline DavidAlfa

  • Super Contributor
  • ***
  • Posts: 5904
  • Country: es
Re: Program doesn't print variable value as expected
« Reply #9 on: February 22, 2022, 11:10:47 pm »
Sincerely, I find a lot more abusive those threads asking some very specific and direct subject, ending in 8 pages of no sense offtopic :popcorn:
Hantek DSO2x1x            Drive        FAQ          DON'T BUY HANTEK! (Aka HALF-MADE)
Stm32 Soldering FW      Forum      Github      Donate
 

Offline brucehoult

  • Super Contributor
  • ***
  • Posts: 4034
  • Country: nz
Re: Program doesn't print variable value as expected
« Reply #10 on: February 23, 2022, 12:46:31 am »
When I compile code it doesn't print value as expected

Code: [Select]
#include<stdio.h>
#include<stdlib.h>

int main()
{
   int x = 1;
   int y = x++;
   
   printf("x : %d\n", x);
   printf("y : %d\n", y);
 
   return 0;
}

x : 2
y : 1

I was expecting 1 should print for variable x.  when I researched about it, I found that  I need to understand difference between pre and post increment oprator.  I tried to figure it out but it's going off the top of my head

Pre-increment won't make any difference to the final value of x. You're incrementing it either way.

Pre-increment of x will make *y* have a different value -- the same as the new value of x instead of the old value.
 

Offline brucehoult

  • Super Contributor
  • ***
  • Posts: 4034
  • Country: nz
Re: Program doesn't print variable value as expected
« Reply #11 on: February 23, 2022, 12:55:50 am »
I find that an abusive use of a forum. A forum's purpose is not to mitigate people's laziness to even open a book. But I'll let Dave be judge of that - it's his forum, not mine. Even if he doesn't care about that, the questions here don't have anything to do with microcontrollers specifically, so it's just polluting the section. Just my 2 cents.

As to the question, just opening a book on C would answer this in a jiffy. As I and a few others note on a regular basis, it's amazing how so many people insist on using C without caring to learn it, and just want to figure it out as they go. And universities which increasingly do not teach it either, yet ask students to use it. It's mind-boggling, and an overall concerning issue, but hey. Let's drown together, it's more fun. =)

I agree with you in all this.

We've been having problems recently on the RISC-V "sw-dev" mailing list with a guy (from the same country, probably not coincidentally) who is trying to port some C package to RISC-V and is having problem after problem, none of which require even the slightest knowledge of RISC-V to solve.

He's asked *twice* now about different code sections that say something like ...

Code: [Select]
#IFDEF USEMEMCPY
   memcpy(x,y,sz);
#ELSE
   ... some code that uses SSE instructions
#ENDIF

... and it blows up the RISC-V compiler when it hits the SSE instructions.

Not exactly hard to solve.

Looking at the code, they'd probably be better off just using memcpy() on x86 too, not least because SSE isn't the latest and greatest thing now like it might have been when the code was written.
 

Offline DavidAlfa

  • Super Contributor
  • ***
  • Posts: 5904
  • Country: es
Re: Program doesn't print variable value as expected
« Reply #12 on: February 23, 2022, 01:20:18 am »
Well, seeing how this is going, I must agree with SiliconWizard
That's very basic stuff, so much that he should be reading C books for begginers or watching YouTube tutorials.

Well...

All examples start with y=6

x = y+1            x=7, y=6
x = y++            x=6, y=7
x = y++ +1       x=7, y=7
x = ++y            x=7, y=7
x = ++y +1       x=8, y=7
x = ++y++        x=7, y=8
x = ++y++ +1   x=8, y=8
Nope OMG.
« Last Edit: February 23, 2022, 01:52:33 pm by DavidAlfa »
Hantek DSO2x1x            Drive        FAQ          DON'T BUY HANTEK! (Aka HALF-MADE)
Stm32 Soldering FW      Forum      Github      Donate
 
The following users thanked this post: Dadu@

Offline Dadu@Topic starter

  • Contributor
  • Posts: 34
  • Country: in
Re: Program doesn't print variable value as expected
« Reply #13 on: February 23, 2022, 05:52:36 am »
So this forum is turning into a free course? One question is fine, but a series of them in a row that are all very basic, I call that a free course.
I am reading books. I asked specific questions which I did not understand while reading the topic. I understand your point that this is microcontroller forum and i should ask microcontroller related question. actually i want to earn c programming for microcotroller but i am not that good in c programming so i am practicing c programming on my PC. Once I understand the basic concept of C programming I will start writing programs for microcontrollers.
 

Offline TomS_

  • Frequent Contributor
  • **
  • Posts: 834
  • Country: gb
Re: Program doesn't print variable value as expected
« Reply #14 on: February 23, 2022, 12:27:17 pm »
So this forum is turning into a free course? One question is fine, but a series of them in a row that are all very basic, I call that a free course.
I am reading books. I asked specific questions which I did not understand while reading the topic. I understand your point that this is microcontroller forum and i should ask microcontroller related question. actually i want to earn c programming for microcotroller but i am not that good in c programming so i am practicing c programming on my PC. Once I understand the basic concept of C programming I will start writing programs for microcontrollers.

If your questions are generic programming related questions, you'd be better off posting them in this forum: https://www.eevblog.com/forum/programming/
 

Offline newbrain

  • Super Contributor
  • ***
  • Posts: 1719
  • Country: se
Re: Program doesn't print variable value as expected
« Reply #15 on: February 23, 2022, 01:42:18 pm »
x = ++y++        x=7, y=8
x = ++y++ +1   x=8, y=8
No.
You are modifying an object twice between sequence points which is definite no-no.
From "J.2 Undefined behavior" in C11:
Quote
— A side effect on a scalar object is unsequenced relative to either a different side effect on the same scalar object or a value computation using the value of the same scalar object (6.5).
This is the "new" formulation, C99 used sequence points but the meaning is exactly the same.

The gist of the problem is that it is not defined in which order the side effects (increments) happen with respect to the act of providing a value for the sub-expression.
Another compiler, or the same a different day, might behave in a completely different way.
The behaviour being undefined, nasal demons are also an option.

This does not even compile, see my post below.
The consideration above are still valid for stuff like x = y++ + ++y;
« Last Edit: February 23, 2022, 02:08:05 pm by newbrain »
Nandemo wa shiranai wa yo, shitteru koto dake.
 

Offline DavidAlfa

  • Super Contributor
  • ***
  • Posts: 5904
  • Country: es
Re: Program doesn't print variable value as expected
« Reply #16 on: February 23, 2022, 01:51:53 pm »
You're right  :palm:
I had never tried that, thought it was possible, didn't seem to cause any undefined behavior:

"x = ++y++" would translate as :
Increment y, copy y to x, increment y.

Edited the screw up and I hope nobody sees it again ever ::)
Hantek DSO2x1x            Drive        FAQ          DON'T BUY HANTEK! (Aka HALF-MADE)
Stm32 Soldering FW      Forum      Github      Donate
 

Offline newbrain

  • Super Contributor
  • ***
  • Posts: 1719
  • Country: se
Re: Program doesn't print variable value as expected
« Reply #17 on: February 23, 2022, 02:05:08 pm »
Actually, now that I think of it, this is a syntax violation so it should really not even compile!

Postfix increment or decrement binds stronger than prefix, and the result of the sub expression is definitely not an lvalue.

All self respecting compilers should give an error.
Nandemo wa shiranai wa yo, shitteru koto dake.
 

Offline DavidAlfa

  • Super Contributor
  • ***
  • Posts: 5904
  • Country: es
Re: Program doesn't print variable value as expected
« Reply #18 on: February 23, 2022, 02:12:05 pm »
Nope, of course it doesn't compile  :phew:
Hantek DSO2x1x            Drive        FAQ          DON'T BUY HANTEK! (Aka HALF-MADE)
Stm32 Soldering FW      Forum      Github      Donate
 

Offline Bassman59

  • Super Contributor
  • ***
  • Posts: 2501
  • Country: us
  • Yes, I do this for a living
Re: Program doesn't print variable value as expected
« Reply #19 on: February 23, 2022, 07:22:15 pm »
Actually, now that I think of it, this is a syntax violation so it should really not even compile!

Postfix increment or decrement binds stronger than prefix, and the result of the sub expression is definitely not an lvalue.

All self respecting compilers should give an error.

If the human reading the code has to spend all of this brain power trying to understand how the compiler handles it, or what the language standard says about it, then ... maybe the human writing the code should not be so clever.
 
The following users thanked this post: newbrain


Share me

Digg  Facebook  SlashDot  Delicious  Technorati  Twitter  Google  Yahoo
Smf