问题描述
我期待答案应该是1.但是在GCC编译器中,Turbo c编译器将结果显示为0.在某些DEV c编译器中显示结果为1.哪一个是正确的,为什么?
I am expecting the answer should come as 1.But in GCC compiler and Turbo c compiler is showing the result as 0.In some DEV c compiler showing the result as 1.Which one is correct and why ?
#include<stdio.h>
int main()
{
int z = 0;
z = 0 || z++;
printf ("%d", z);
return 0;
}
我尝试过:
我在Dev c,GCC和Turbo c编译器中尝试过。
What I have tried:
I have tried in Dev c , GCC and Turbo c compiler.
推荐答案
a || b
第一个表达式的布尔结果
The boolean result of the first expression
z = 0
是赋值后左操作数 z
的值。当它为零时,布尔结果为false。你可以检查这个:
is the value of the left operand z
after the assignment. When that is zero, the boolean result is false. You can check this:
int z = 0;
int a = (z = 0) ? 1 : 0;
int b = (z = 1) ? 1 : 0;
printf("%d %d\n", a, b);
这应打印 0 1
包含所有编译器。
一旦评估了左项的布尔结果,第二次操作只应在第一次操作时执行:
This should print 0 1
with all compilers.
Once the boolean result of the left term has been evaluated, the second operation should be only executed when the first was true:
int b = (z = 0) ? 1 : 0;
if (b)
b = (z++) ? 1: 0;
然后 z
将仍然为零,因为未执行增量操作。
以上是错误的(谢谢NV)!
如果,它应该是偏离的!b)
[/ EDIT2]
另请注意,优化编译器可能会检测到逻辑操作的结果始终为false并将零分配给 z
甚至跳过该行
A compiler that prints "1" here is not conforming to the C standard.
Note also that optimising compilers might detect that the result of the logical operation is always false and assign zero to z
or even skip the line
z = 0 || z++;
因为 z
已经在上一行中设置为零。
[/ EDIT]
解决方案3指出了问题。
行为未定义,如警告所示。
试试这个:
because z
has been already set to zero in the previous line.
[/EDIT]
Solution 3 is pointing out the problem.
The behaviour is undefined as indicated by the warning.
Try this:
int z = 0;
z = 0 || z++;
printf ("z: %d\n", z);
(z = 0) || (z++);
printf ("z: %d\n", z);
使用GCC,它将打印
With GCC, it will print
z: 0
z: 1
[/ EDIT2]
[/EDIT2]
gcc -Wall mytest.c
mytest.c: In function ‘main’:
mytest.c:6:7: warning: operation on ‘z’ may be undefined [-Wsequence-point]
z = 0 || z++;
那就是你遇到 C
编程语言的一个黑暗角落。例如,请参见 []。
作为附注,启用所有警告( -Wall $毕竟c $ c>
gcc
可能证明它本身很有用。
That is you hit a dark corner of the C
programming language. See, for instance Sequence point - Wikipedia[^].
As a side note, enabling all the warnings (-Wall
with gcc
may prove itself useful, after all).
int z = 0;
z = 0 || z++;
这又是在z分配之前或之后是否执行后增量的问题。
This is again a question of whether the post-increment is performed before or after the assignment to z.
这篇关于不了解基本的C问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!