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

use*_*127 2 c++ math comparison function return-value

请考虑以下代码:

   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");
   }
Run Code Online (Sandbox Code Playgroud)

正如评论所示,我不明白为什么在与另一个值工作进行比较之前需要一个临时变量来存储数学计算的结果.

das*_*ght 8

你得到true那里的原因是因为减法的结果是无符号的.反过来,这是因为size_t,返回类型strlen()是无符号的,并且它足够大以至于int转换为其类型而不是相反.

将减法结果分配给有符号int变量时tmp,会再次对结果进行签名,因此比较将按预期进行.

通常,如果您怀疑结果可能变为负数,则应该非常小心减去无符号值.如果您不是100%确定,请使用签名类型,或首先避免减法.例如,上述条件的合法替代将是

if (strlen(foo) <= 5)
    ...
Run Code Online (Sandbox Code Playgroud)

  • @Svalorzen,如果它不符合§4.7[conv.integral]的话,它是一个实现定义的值. (2认同)