i++


最近在准备找工作了。

看到程序员面试宝典上面有这样两段代码:


第一段是这样的:


    #include<iostream> 
    using namespace std;  
    int main()  
    {  
    int a,x;  
    for(a=0,x=0;a<=1 &&!x++;a++)  
    {  
      a++;  
     
    }  
    cout<<a<<x<<endl;  
    return 0;  
    } 


第二段是这样的:


    #include<iostream> 
    using namespace std;  
    int main()  
    {  
    int a,x;  
    for(a=0,x=0;a<=1 &&!x++;)  
    {  
      a++;  
     
    }  
    cout<<a<<x<<endl;  
    return 0;  
    } 


问这两段运行结果的差别。



如果知道了3点,这个答案会很清晰:


(1)

符号的运算先后顺序,可以参考这里:http://en.cppreference.com/w/cpp/language/operator_precedence

因此,这个题目,没有什么陷阱。

postfix 的 ++的优先级非常高。

而逻辑与的优先级是最低的。


(2)

然后要知道for loop是怎么执行的。


可以参考这里:http://www.cplusplus.com/doc/tutorial/control/


for (initialization; condition; increase) statement;


  1. initialization is executed. Generally, this declares a counter variable, and sets it to some initial value. This is executed a single time, at the beginning of the loop.
  2. condition is checked. If it is true, the loop continues; otherwise, the loop ends, andstatement is skipped, going directly to step 5.
  3. statement is executed. As usual, it can be either a single statement or a block enclosed in curly braces{ }.
  4. increase is executed, and the loop gets back to step 2.
  5. the loop ends: execution continues by the next statement after it.

(重点在于括号里的increase 是再什么时候执行,是要在statement执行之后。)


(3)

逻辑与 A && B

只要A为false,B就不再evaluate了。



然后,答案就很清晰了。



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值