#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 | 3993 |
2 | jiangly | 3743 |
3 | orzdevinwang | 3707 |
4 | Radewoosh | 3627 |
5 | jqdai0815 | 3620 |
6 | Benq | 3564 |
7 | Kevin114514 | 3443 |
8 | ksun48 | 3434 |
9 | Rewinding | 3397 |
10 | Um_nik | 3396 |
# | User | Contrib. |
---|---|---|
1 | cry | 167 |
2 | Um_nik | 163 |
3 | maomao90 | 162 |
3 | atcoder_official | 162 |
5 | adamant | 159 |
6 | -is-this-fft- | 158 |
7 | awoo | 155 |
8 | TheScrasse | 154 |
9 | Dominater069 | 153 |
10 | nor | 152 |
#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;