各位好
我看不出來以下兩個 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 取負真的是溢位