How is i==(20||10) evaluated?

南楼画角 提交于 2019-11-26 23:44:09

问题


#include <stdio.h>
int main(void)
{
   int i=10;
   if(i==(20||10))
       printf("True");
   else
       printf("False");
   return 0;
}

This gives the output False.

Please explain to me how does this program work?


回答1:


This line if(i==(20||10)) always evaluates to i==1 as Alk said in comments - (20||10) evaluates to 1, hence when you compare i == 1, that is why you get False as the output. A non-Zero value in C implies true.

Read about Short-circuit evaluation

Perhaps this is what you wanted:

int i=10;
if(i==20 || i == 10)
    printf("True");
else
    printf("False");



回答2:


look at if(i==(20||10)). Due to the inner parentheses, 20||10 is evaluated first, yielding 1. Then, variable i, whose value is 10 is compared to 1, resulting 0.

In C, and 0 stands for False, while all non-zero values means True. So the condition comes to be False. Thus, "False" is printed.



来源:https://stackoverflow.com/questions/35078899/how-is-i-2010-evaluated

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!