#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 | 3985 |
2 | jiangly | 3814 |
3 | jqdai0815 | 3682 |
4 | Benq | 3529 |
5 | orzdevinwang | 3526 |
6 | ksun48 | 3517 |
7 | Radewoosh | 3410 |
8 | hos.lyric | 3399 |
9 | ecnerwala | 3392 |
9 | Um_nik | 3392 |
# | User | Contrib. |
---|---|---|
1 | cry | 169 |
2 | maomao90 | 162 |
2 | Um_nik | 162 |
4 | atcoder_official | 161 |
5 | djm03178 | 158 |
6 | -is-this-fft- | 157 |
7 | adamant | 155 |
8 | awoo | 154 |
8 | Dominater069 | 154 |
10 | luogu_official | 150 |
#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;