gpt4 book ai didi

c++ - 我想知道是否有可能在使用调试器Visual Studio代码进入if语句之前检查if语句的计算结果

转载 作者:行者123 更新时间:2023-12-02 10:09:10 26 4
gpt4 key购买 nike

我有正在使用的C代码,老实说,我不明白它的确切工作原理(以前从未使用过if语句)。这是代码:

#include<stdio.h>

int main(int argc, char const *argv[])
{
int x = 2, y = 0;
if (x = ++y)
{
printf("%d is equal to %d\n", x,y);
}
else
{
printf("%d is not equal %d", x, y);
}
}
出于某种原因,似乎赋值运算符也在充当相等运算符?因为当它求值时,X将为1,Y将为1,因此它将移至if中的第一个主体。但是,如果我执行 x = y++,它将转到第二条语句。只是让我感到困惑,因为不应该将相等视为 ==而不是 =

最佳答案

这是代码的语义修复:

#include<stdio.h>

int main(int argc, char const *argv[])
{
int x = 2, y = 0;
if (x = ++y)
{
printf("y has been incremented and copied to x, which is now non-zero\n");
}
else
{
printf("y has been incremented and copied to x, which is now zero\n");
}
}

#include<stdio.h>

int main(int argc, char const *argv[])
{
int x = 2, y = 0;
if (x = y++)
{
printf("y has been copied to x and then y incremented, x is now non-zero (y was non-zero)\n");
}
else
{
printf("y has been copied to x and then y incremented, x is now zero (y was zero)\n");
}
}

作为一般原则,我主张使用 Yoda表达式,其中将不可分配的值放在左侧,例如 if (1 == x)。这可以防止意外分配。

关于c++ - 我想知道是否有可能在使用调试器Visual Studio代码进入if语句之前检查if语句的计算结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64380654/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com