问题描述
为什么可以这样:
if(int i = 1) {
}
...而以下内容会产生错误?
...whereas the following produces errors?
if((int i = 1)) {
}
在g ++(4.4.5)下,后者给出:
Under g++ (4.4.5) the latter gives:
顺便说一句,我要问的原因是因为这个答案:
Incidentally, the reason I'm asking is because of this answer: Seeing what class an object is
我正在尝试寻找一种方法条件更易读。通常,我更喜欢例如:
I'm trying to find a way to make the condition more readable. Usually, I would prefer, for example:
if((x = y) != 0) {
到
if(x = y) {
...因为它更具可读性,并且使编译器评论无声,提示我可能使用了错误的运算符。如果我使用声明作为条件,它不会产生警告,但可读性仍然会受到影响。
...since it's more readable and silences compiler 'comments' suggesting I might have used the wrong operator. If I'm using a declaration as a condition, it doesn't produce the warning, but the readability still seems to suffer.
推荐答案
这是因为C ++标准是6.4 p1。
It's because of the C++ standard, 6.4 p1.
选择说明:
if ( condition ) statement
if ( condition ) statement else statement
switch ( condition ) statement
条件:
expression
type-specifier-seq declarator = assignment-expression
这篇关于声明为条件-添加括号会导致错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!