why negative number is taken as true in condition statement? [duplicate]

六月ゝ 毕业季﹏ 提交于 2021-02-05 12:31:52

问题


Here i am confused with condition statement which has negative number,if in the condition only negative number is given as if(-1) then it is true but if (-1>0) then it become false please explain any one thanks in advance

if(-1) // This true why and how?
if(-1>0)//This is false why and how

Now what is impact in below code please help to understand

#include <stdio.h>
#include <string.h>

main()
{
  char a[]="he";
  char b[]="she";
  if(strlen(a)-strlen(b)>0)//how it is true ?if(2-3>0)i.e if(-3>0) which is false
    //here why it is true                   
  {
    printf("-ve greater then 0 ");
  }
  else 
  {
    printf(" not greater then 0");
  }
}

回答1:


if(-1) // This true why and how?

Any non-zero number is evaluated as true.

if(-1>0) //This is false why and how

-1 is less than 0 that's why expression -1 > 0 evaluated to false.

if(strlen(a)-strlen(b)>0) //how it is true ?if(2-3>0)i.e if(-3>0) which is false //here why it is true

strlen returns size_t type which is unsigned. The result of strlen(a)-strlen(b would be an unsigned int. But -1 in not unsigned, therefore it is converted to unsigned before comparison.strlen(a)-strlen(b)>0 will result in comparison UINT_MAX -1 > 0




回答2:


Function strlen() returns a size_t, which is an unsigned integer type.

For this reason, strlen(a)-strlen(b) is an unsigned subtraction. It will produce a nonnegative number because it will produce a size_t and all values of size_t are nonnegative.




回答3:


Every value, which is not 0, gets evaluated as true in if sentence.




回答4:


Adding to existing answer:

char a[]="he";
char b[]="she";
if(strlen(a)-strlen(b)>0)

strlen returns size_t. Result of different of size_t would be size_t too. Unsigned numbers are always >= 0. In your case it is similar to

if((2U - 3U) > 0U)

See live code here.

You should rewrite the condition to:

if(strlen(a) > strlen(b))



回答5:


The idea that any nonzero number is considered true is a very old concept in computer science. Think of it as treating the raw bits as inputs to a big OR gate. If any bit is a one, then the output is a one (or true). A negative number is a number where the most significant bit, the sign bit, is a one.



来源:https://stackoverflow.com/questions/24673795/why-negative-number-is-taken-as-true-in-condition-statement

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