나는 내가 작업하고 있던이 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)
. 이것은 우발적 인 할당을 방지합니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다