我是编程新手。现在,我试图学习C语言中运算符的优先级。我试图分析下面给出的代码。
#include<stdio.h>
int main()
{
int x, y, z;
x = y = z= -1;
z = ++x&&++y&&++z;
printf("x = %d y = %d z = %d", x, y ,z);
}
在了解了运算符的优先级之后,我了解到一元运算符具有更高的优先级。所以在上面的代码
z = ++0&&++0&&++0;
所以x,y,z的值等于零,对吧?但是在编译后我得到了x = 0,y = -1和z = 0的答案。
谁能帮我解决这个问题?
在评估逻辑与时,如果第一个表达式为零/假,则它将不评估其余表达式。所以
z = ++x&&++y&&++z; // It first increment x, due to pre-increment it becomes zero.
// so it wont evaluate the remaining expression in that equation due to Logical AND. it returns 0. (x=0,y=-1,z=-1)
// but you are assigning return value 0 to z
z=0;
尝试以下代码段-
int x, y, z,temp;
x = y = z= -1;
temp = ++x&&++y&&++z;
printf("x = %d y = %d z = %d temp= %d", x, y ,z,temp); // Output 0,-1,-1,0
x = y = z= -1;
temp = ++x || ++y&&++z; // But in Logical OR if first expression is true means it wont execute the remaining expression
printf("x = %d y = %d z = %d temp= %d", x, y ,z,temp); // Output 0,0,-1,0
x = y = z= -1;
temp = ++x || ++y || ++z;
printf("x = %d y = %d z = %d temp= %d", x, y ,z,temp); // Output 0,0,0,0
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句