简体   繁体   English

C ++数学比较使用函数返回值不起作用

[英]C++ mathematical comparison using function return value not working

Consider the following code: 请考虑以下代码:

   char foo[32] = "123456";
   printf("strlen(foo) = %d\n", strlen(foo));
   if ((5 - strlen(foo)) > 0)
   {
      //This statement prints because the comparison above returns true, why?
      printf("String must be less than 5 characters, test 1\n");
   }

   int tmp;
   if ((tmp = 5-strlen(foo)) > 0)
   {
      //This statement does not print and makes since
      printf("String must be less than 5 characters, test 2\n");
   }

As the comments indicate, I do not understand why a temporary variable is needed to store the result of the mathematical calculation before comparisons to another value work. 正如评论所示,我不明白为什么在与另一个值工作进行比较之前需要一个临时变量来存储数学计算的结果。

The reason why you get a true there is because the result of the subtraction is unsigned . 你得到true原因是因为减法的结果是无符号的 This, in turn, is because size_t , the return type of strlen() , is unsigned, and it's large enough that int got converted to its type rather than the other way around. 反过来,这是因为size_tstrlen()的返回类型是无符号的,而且它足够大以至于int转换为它的类型而不是相反的方式。

When you assign the result of the subtraction to a signed int variable tmp , you make the result signed again, so the comparison works as expected. 将减法的结果分配给signed int变量tmp ,再次对结果进行签名,以便比较按预期工作。

In general, you should be very careful with subtraction of unsigned values if you suspect that the result might become negative. 通常,如果您怀疑结果可能变为负数,则应该非常小心减去无符号值。 If you are not 100% sure, use a signed type, or avoid subtractions in the first place. 如果您不是100%确定,请使用签名类型,或首先避免减法。 For example, a legitimate replacement for your condition above would be 例如,上述条件的合法替代将是

if (strlen(foo) <= 5)
    ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM