![](/img/trans.png)
[英]Stepping past lines of source code causes Visual Studio debugger to exit?
[英]I was wondering if its possible to check what an if statement evaluates to before stepping into it using debugger visual studio code
我有我正在處理的這個 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 時,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)
。 這可以防止意外分配。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.