前言
这个问题是指使用类似if() ... else或类似条件语句的最常见(初学者)错误的规范集合.答案旨在描述运行时的意外行为,语法缺陷和误解
Run Code Online (Sandbox Code Playgroud)if(x) {} else (y) {}
不应该在这里解决.
Run Code Online (Sandbox Code Playgroud)if(x = 1) // ...平等比较用表达式表示
==.=是一个赋值,结果被评估为强制转换为bool.即任何评估!= 0结果的值true.作为预防机制,请考虑以下表达式:
Run Code Online (Sandbox Code Playgroud)if(1 = x) // invalid assignment compilation error! if(1 == x) // valid equality comparison通过始终将常量放在表达式的左侧,可以避免错误地使用赋值运算符.编译器将标记触发无效赋值错误的任何错误.
Run Code Online (Sandbox Code Playgroud)if(answer == 'y' || 'Y')变化:
if(answer == 'y','Y')
必须通过单独的比较来测试条件.该||运营商绑定不去做怎么在这里期待.请if(answer == 'y' || answer == 'Y')改用.
Run Code Online (Sandbox Code Playgroud)if (0 < x < 42)在Python有效的语法,与预期的行为,该语法是在C++中有效,但解析为
if ((0 < x) < 42)这样false/true转换到0/1,然后对所测试< 42- >总是true.条件必须通过单独的比较进行测试:if (0 < x && x < 42)
Run Code Online (Sandbox Code Playgroud)if(mycondition); { // Why this code is always executed ??? }声明
;后有多余的内容if()。
Run Code Online (Sandbox Code Playgroud)if(mycondition) statement1(); statement2(); // Why this code is always executed ???该代码等效于
Run Code Online (Sandbox Code Playgroud)if(mycondition) { statement1(); } statement2();
statement2();在条件块的范围之外。添加{}到组语句。
Run Code Online (Sandbox Code Playgroud)if (mycondition) if (mycondition2) statement1(); else statement2();该代码等效于
Run Code Online (Sandbox Code Playgroud)if(mycondition) { if (mycondition2) statement1(); else statement2(); }
else申请以前的if。添加{}:Run Code Online (Sandbox Code Playgroud)if (mycondition) { if (mycondition2) statement1(); } else statement2();
这同样适用于任何错误放置;在循环语句中的语句,例如
Run Code Online (Sandbox Code Playgroud)for(int x = 0;x < 5;++x); // ^ { // statements executed only once }
要么
Run Code Online (Sandbox Code Playgroud)while(x < 5); // ^ { // statements executed only once }
| 归档时间: |
|
| 查看次数: |
467 次 |
| 最近记录: |