#include <stdio.h>
#include <string.h>
int main(){
int y = 7 , z = 8 ;
int *p;
p = &y ;
*p = (++z)+(y++);
printf("%d\n",*p);
return 0;
}
This program's output is 8 Anyone know how is this?
# | User | Rating |
---|---|---|
1 | Radewoosh | 3759 |
2 | orzdevinwang | 3697 |
3 | jiangly | 3662 |
4 | Benq | 3644 |
5 | -0.5 | 3545 |
6 | ecnerwala | 3505 |
7 | tourist | 3486 |
8 | inaFSTream | 3478 |
9 | maroonrk | 3454 |
10 | Rebelz | 3415 |
# | User | Contrib. |
---|---|---|
1 | adamant | 173 |
2 | awoo | 166 |
3 | nor | 165 |
4 | SecondThread | 162 |
4 | maroonrk | 162 |
6 | BledDest | 161 |
6 | Um_nik | 161 |
8 | -is-this-fft- | 149 |
9 | Geothermal | 146 |
10 | ko_osaga | 142 |
#include <stdio.h>
#include <string.h>
int main(){
int y = 7 , z = 8 ;
int *p;
p = &y ;
*p = (++z)+(y++);
printf("%d\n",*p);
return 0;
}
This program's output is 8 Anyone know how is this?
Name |
---|
hahaha XD.
MS C++ outputs 17 and GNU C++ outputs 8 :)
I think that's undefined behaviour
According to Kernighan & Ritchie's book The C Programming Language, 2nd Edition (ANSI C), by Prentice Hall, page 52:
"C, like most languages, does not specify the order in which the operands of an operator are evaluated. (The exceptions are &&, ||, ?: and ','.)"
Right on the next page (53) it continues with an example:
"printf("%d %d\n", ++n, power(2, n)); /* WRONG */ ... The solution, of course, is to write ++n; printf("%d %d\n", n, power(2, n));"
and at last, the expression "a[i] = i++;" is mentioned as a "one unhappy situation".
-
Wrong. The order of evaluation of the function arguments is not specified.
The C99 standard, paragraph 6.5.2.3.10:
I just leave it here.
if 10=1+2+3+4 and 16=4+4+4+4 then where did "11" come from?
If it helps, this is how compiler translate the code above:
11 in %eax.
1.step i = 1 then z = i + ++i + ++i + ++i
2.step i = 2 then z = 2 + 2 + ++i + ++i
3.step i = 3 then z = 4 + 3 + ++i ;
4.step i = 4 then z = 7 + 4
final i = 4 , z = 11
*p=y=7; (y++)-->(y=y+1); *p=y=8;