考试酷解析——A12_Precedence and Order of Evaluation-1

解析

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.

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值