0

i have been working with this C problem for quite a while now, but dint get the satidfactory answer for it. i have got four pieces of code as follows:

code 1:-
#include <stdio.h>
int i=10;
int main()
{
    printf("%d %d %d", ++i, ++i, ++i);
    return 0;
}
output:
13 12 11

code 2:-
#include <stdio.h>
int main()
{
    static int i=10;
    printf("%d %d %d", ++i, ++i, ++i);
    return 0;
}
output:
13 12 11

code 3:-
#include <stdio.h>
int main()
{
    volatile int i=10;
    printf("%d %d %d", ++i, ++i, ++i);
    return 0;
}
output:
13 12 11

code 4:-
#include <stdio.h>
int main()
{
    int i=10;
    printf("%d %d %d", ++i, ++i, ++i);
    return 0;
}
output:
13 13 13

i ran the above code on https://www.onlinegdb.com/, and the following results. i have gone through the concepts of precedence and associativity in c, and have a good understanding of memory segments and allocation in c and thus understand the working of static and volatile keywords, but even after going through the concepts again and again i an not able to understand why the results of code 1, 2, 3 are coming out to be 13 12 11 shouldnt they give the same results as code 4, that is 13 13 13.

i was expecting that code 1, 2, 3 should be resulting in the same results as code 4. but they are not.

user694733
  • 15,208
  • 2
  • 42
  • 68
  • 1
    This is by far the #1 FAQ for C on SO. It has nothing to do with precedence/associativity, the code is simply broken without any well-defined outcome. See the linked duplicate. – Lundin Mar 21 '23 at 09:44
  • frankly the most puzzling part of these questions is why ppl spend so much time with it. I suppose you know that none of this is really needed to print `1 2 3` on the console. Also it shouldnt be something that is encountered in legacy too often. – 463035818_is_not_an_ai Mar 21 '23 at 09:47
  • It seems the reason is in compiler optimization. – i486 Mar 21 '23 at 09:49
  • @463035818_is_not_a_number See [this answer](https://stackoverflow.com/questions/949433/why-are-these-constructs-using-pre-and-post-increment-undefined-behavior/51876456#51876456) at the linked duplicate. No, no one would write that code in a real program, but if you're a beginner just learning about `++` and `--`, it's evidently quite natural to throw several of them into a single `printf` statement like this, quietly assuming that the arguments are evaluated left-to-right, and then get badly confused by the wildly counterintuitive results. – Steve Summit Mar 21 '23 at 11:23
  • @ShivamGupta Please break it up into three separate statements: `printf("%d ", ++i); printf("%d ", ++i); printf("%d\n", ++i);`. Then it will have well-defined and sensible results. – Steve Summit Mar 21 '23 at 11:26

0 Answers0