i++

来源:互联网 发布:js formatdate函数 编辑:程序博客网 时间:2024/04/29 00:12


最近在准备找工作了。

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


第一段是这样的:


    #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
原创粉丝点击