问题描述
对于以下程序,我得到的输出不是我预期的那个
。
main()
{
int i = 3;
i = i ++;
printf("%d \ n",i);
}
输出为3,我预期的输出为4.
这是一种未定义的行为吗?
谢谢,
Deepak
Hi,
For the following program the output I''m getting is not the one I
expected.
main()
{
int i = 3;
i = i++;
printf("%d\n", i);
}
Output is 3 and the output I expected was 4.
Is it an undefined behaviour?
Thanks,
Deepak
推荐答案
为什么你会期待4? i ++的结果是i的原始值。
-
Ian Collins。
Why would you expect 4? The result of i++ is the original value of i.
--
Ian Collins.
这是在FAQ中。
3.3:我已经尝试过代码
int i = 3;
i = i ++;
在几个编译器上。有些人给了我3的值,有些给了4。
哪个编译器是正确的?
答:没有正确答案;表达式未定义。请参阅
问题3.1,3.8,3.9和11.33。 (另请注意,
i ++ + ++ i与i + 1相同。如果你想增加i,
使用i = i + 1,i + = 1,i ++或++ i,不是某种组合。另见
问题3.12。)
-
char a [] =" \ n .CJacehknorstu" ;; int putchar(int); int main(void){unsigned long b []
= {0x67dffdff,0x9aa9aa6a,0xa77ffda9,0x7da6aa6a,0xa6 7f6aaa,0xaa9aa9f6,0x11f6},* p
= b,i = 24; for(; p + =!* p; * p / = 4)switch(0 [p]& 3)case 0:{return 0; for(p - ; i - ; i - )case +
2:{i ++; if(i)break; else default:continue; if(0)case 1:putchar(a [i& 15]); break;}}}
This is in the FAQ.
3.3:I''ve experimented with the code
int i = 3;
i = i++;
on several compilers. Some gave i the value 3, and some gave 4.
Which compiler is correct?
A:There is no correct answer; the expression is undefined. See
questions 3.1, 3.8, 3.9, and 11.33. (Also, note that neither
i++ nor ++i is the same as i+1. If you want to increment i,
use i=i+1, i+=1, i++, or ++i, not some combination. See also
question 3.12.)
--
char a[]="\n .CJacehknorstu";int putchar(int);int main(void){unsigned long b[]
={0x67dffdff,0x9aa9aa6a,0xa77ffda9,0x7da6aa6a,0xa6 7f6aaa,0xaa9aa9f6,0x11f6},*p
=b,i=24;for(;p+=!*p;*p/=4)switch(0[p]&3)case 0:{return 0;for(p--;i--;i--)case+
2:{i++;if(i)break;else default:continue;if(0)case 1:putchar(a[i&15]);break;}}}
为什么你会期望4? i ++的结果是i的原始值。
Why would you expect 4? The result of i++ is the original value of i.
是的,这是期待3的好参数,但可能是OP的'b $ b b期望是该程序'的未定义的行为会导致我们可能不会期望的价值
a值 - 而男孩,他感到惊讶!
未定义的行为不是/不需要/是奇怪的行为。
顺便说一下,我在家里运行程序并获得输出:a
黄色填充。
-
Richard Heathfield< http://www.cpax.org.uk>
电子邮件:-www。 + rjh @
谷歌用户:< http://www.cpax.org.uk/prg/writings/googly.php>
Usenet是一个奇怪的放置" - dmr 1999年7月29日
Yes, which is a good argument for expecting 3, but presumably the OP''s
expectation was that the program''s undefined behaviour would result in
a value that we might not expect - and boy, was he surprised!
Undefined behaviour is not /required/ to be bizarre behaviour.
Incidentally, I ran the program at home and got the output: "a
suffusion of yellow".
--
Richard Heathfield <http://www.cpax.org.uk>
Email: -www. +rjh@
Google users: <http://www.cpax.org.uk/prg/writings/googly.php>
"Usenet is a strange place" - dmr 29 July 1999
这篇关于增量运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!