在C ++中,使用条件(if)语句最常见的陷阱是什么? [英] Which are the most common pitfalls with conditional (if) statements in C++?

查看:46
本文介绍了在C ++中,使用条件(if)语句最常见的陷阱是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

序言

此问题的意思是使用条件代码(例如 if()... else 或类似条件)对最常见的(初学者)错误进行规范收集.答案旨在描述运行时的意外行为,句法缺陷和误解,例如

This question is meant as a canonical collection of the most frequent (beginner) mistakes using conditional statements like if() ... else or similar. Answers are meant to describe unexpected behaviors at runtime, syntactical flaws and misconceptions like

if(x) {}
else (y) {}

在这里不应该解决.

推荐答案

对条件表达式的误解

  • if(x = 1) // ...
    

    平等比较是使用 == 表示的. = 是一个赋值,其结果作为对 bool cast 的评估.IE.任何评估为!= 0 的值都将生成 true .作为一种预防机制,请考虑以下表达式:

    Equality comparisons are expressed using the ==. = is an assignment, and the result is evaluated as a cast to bool. I.e. any value evaluated to != 0 results in true. As a prevention mechanism consider the below expressions:

  •    if(1 = x)  // invalid assignment compilation error!
       if(1 == x) // valid equality comparison
    

    可以通过始终将常量放在表达式的左侧来避免错误使用赋值运算符.编译器将标记任何触发无效分配错误的错误.

    A wrong use of an assignment operator can be avoided by always placing the constant on the left hand side of the expression. The compiler will flag any mistake triggering an invalid assignment error.

  • if(answer == 'y' || 'Y')
    

    变量: if(answer =='y','Y')
    条件必须通过单独的比较进行测试. ||| 运算符绑定不能满足此处的预期.改为使用 if(answer =='y'|| answer =='Y').

    Variations: if(answer == 'y','Y')
    Conditions must be tested with separate comparisons. The || operator binding doesn't do what's expected here. Use if(answer == 'y' || answer == 'Y')instead.

  • if (0 < x < 42)  
    

    Python中的有效语法,具有预期的行为,该语法在C ++中有效,但是被解析为 if((0 ,所以 false / true 转换为 0 / 1 ,然后针对<42 ->始终为 true .条件必须通过单独的比较进行测试: if(0< x&& x< 42)

    Valid syntax in Python, with expected behaviour, that syntax is valid in C++, but parsed as if ((0 < x) < 42) so false/true converted to 0/1 and then tested against < 42 -> always true. Condition must be tested with separate comparisons: if (0 < x && x < 42)

  • 这篇关于在C ++中,使用条件(if)语句最常见的陷阱是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆