这让我有些迷惑,因为我似乎找不到这段代码的任何问题。
无论如何,这是谜语:
假设有人向 a, b
中注入(inject)一个随机值:
int foo(int a, int b)
{
return b ? (a / b): 0;
}
b != 0
总是!
是否可能出现整数除零异常?
我开始认为这是一个恶作剧,然而......
注意:
这个问题是在一个 session 上发表的,作者有可能特定于一个编译器/架构,这是有问题的。
最佳答案
不,这里不可能除以零。
引用 C11
,章节 §6.5.15,条件运算符,(强调我的)
The first operand is evaluated; there is a sequence point between its evaluation and the evaluation of the second or third operand (whichever is evaluated). The second operand is evaluated only if the first compares unequal to 0; the third operand is evaluated only if the first compares equal to 0; [...]
因此,如果 b
为 0,则表达式 (a/b)
将不会被计算。
也就是说,正如注释:
- 除法为整数除法。
- 如果你有一个包装器,确保
b != 0
,那么你可以减少整个函数调用,只需编写someVar = a/b;
<
此外,我不知道有任何架构(可能)会改变上述行为。
关于c - 在这个条件语句中是否有被零除的可能性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38423065/