各位好
我看不出来以下两个 function 有什么不同,请各位指教。
1.Do cmp1 and cmp2 print the same message for all possible inputs?
if not , please provide a case where they print it.
1.Do cmp1 and cmp2 return the same value for all possible inputs?
if not , please provide a case where they return it.
#define ABS(n) ((n<0)? -n:n)
int cmp1(int a , int b)
{
int result;
a=(a<0) ? -a: a;
b=(b<0) ? -b: b;
result=(a==b);
if(result)
printf("The absolute values of %d and %d are the same.",a,b);
else
printf("The absolute values of %d and %d are different.",a,b);
return result;
}
int cmp2(int a , int b)
{
int result=(ABS(a)==ABS(b));
if(result)
printf("The absolute values of %d and %d are the same.",a,b);
else
printf("The absolute values of %d and %d are different.",a,b);
return result;
}
作者: ichunlai (^_^) 2024-01-16 09:06:00
cmp2的ABS是macro,有丢到编译器看看吗?我也很好奇结果是啥啊,我猜cmp2在任何负值(譬如-1)可能会变成--1之类的状况跑了一下,我上面的回答没想清楚,题目1的答案是(int_min+1)到-1之间print的值不同,原因同一楼所述,题目二是全相同
作者:
LPH66 (-6.2598534e+18f)
2024-01-18 05:21:00有号数对 INT_MIN 取负可能溢位, 而有号数溢位是 UB然后其实这一点对 cmp1 和 cmp2 都是一样的(因为不论是否经过宏, 两边都有直接取负的运算)嘛, 讲“可能”溢位是早期 C/C++ 的定义了, C++20 的有号数固定为二补数所以 INT_MIN 取负真的是溢位