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;
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.condition
is checked. If it is true, the loop continues; otherwise, the loop ends, andstatement
is skipped, going directly to step 5.statement
is executed. As usual, it can be either a single statement or a block enclosed in curly braces{ }
.increase
is executed, and the loop gets back to step 2.- the loop ends: execution continues by the next statement after it.
(重点在于括号里的increase 是再什么时候执行,是要在statement执行之后。)
(3)
逻辑与 A && B
只要A为false,B就不再evaluate了。
然后,答案就很清晰了。
0 0
- I
- I
- ++i
- I
- I
- i
- ++i
- i++
- (++i) + (++i) + (++i) + (++i)
- i++
- i
- i
- I++,I--,++I,--I
- I
- i++
- i++
- I
- ++i,--i,i++,i--
- 配置rsync远程数据同步服务详解
- Linux系统之LVS负载均衡群集
- LVS+Keepalived实现高可用群集
- 详解某医院HP-EVA4100数据恢复案例
- 写给领导的《年终总结》
- i++
- 详解MBR分区结构以及GPT分区结构
- FAT32文件系统详解
- 分析NTFS文件系统内部结构
- 浅谈Linux下的EXT3文件系统
- 解析Linux环境下RAID 6的Q校验算法
- 某法院HP-P4500存储数据恢复案例
- Intent和PendingIntent的区别
- [顶级私货]刚从驾校那偷出来的,以后你们可以自己自学了