#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 | tourist | 4009 |
2 | jiangly | 3823 |
3 | Benq | 3738 |
4 | Radewoosh | 3633 |
5 | jqdai0815 | 3620 |
6 | orzdevinwang | 3529 |
7 | ecnerwala | 3446 |
8 | Um_nik | 3396 |
9 | ksun48 | 3390 |
10 | gamegame | 3386 |
# | User | Contrib. |
---|---|---|
1 | cry | 165 |
2 | maomao90 | 164 |
3 | Um_nik | 163 |
4 | atcoder_official | 160 |
4 | adamant | 160 |
6 | -is-this-fft- | 158 |
7 | awoo | 157 |
8 | TheScrasse | 154 |
8 | Dominater069 | 154 |
8 | nor | 154 |
#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;