解析
arithmetic operator are not sequence pointin C, but logical | | and && are.
第一题:
//What is the output of this C code?
#include <stdio.h>
void reverse(int i)
int main()
{
reverse(1);
}
void reverse(int i)
{
if (i > 5)
exit(0);
printf("%d\n", i);
return reverse(i++);
}
reverse(i++)返回的仍是reverse(i),因此会陷入死循环,出现stack overflow,可改成reverse(++i)。
第四题:
//What is the value of i and j in the below code?
#include <stdio.h>
int x = 0;
int main()
{
int i = (f() + g()) || g();
int j = g() || (f() + g());
}
int f()
{
if (x == 0)
return x + 1;
else
return x - 1;
}
int g()
{
return x++;
}
这是有关顺序点的测试点
1. 顺序点内的语句执行顺序不确定,题目的代码会引起undefined behavior
2. 逻辑且、或运算符是短路求值的
不要纠结undefined behavior具体是多少
undefined behavior指在顺序点内,多次修改同一变量
第五题:
//What is the value of i and j in the below code?
#include <stdio.h>
int x = 0;
int main()
{
int i = (f() + g()) | g(); //bitwise or
int j = g() | (f() + g()); //bitwise or
}
int f()
{
if (x == 0)
return x + 1;
else
return x - 1;
}
int g()
{
return x++;
}
由于 | 不是顺序点,所以i的值可计算出来为1,但是j计算出来是7,所以只有选项i=1,j是undefined behaviour符合。
第十题:
//What is the output of this C code?
#include <stdio.h>
int main()
{
int y = 2;
int z = y +(y = 10);
printf("%d\n", z);
}
()有最高的优先级,所以先计算这一部分,最终结果是20.