2010-12-13 32 views
2

为什么这是正确的:宣布为条件 - 加括号会导致错误

if(int i = 1) { 
} 

...而以下产生错误?

if((int i = 1)) { 
} 

在G ++(4.4.5),后者给出了:

test.cpp:7: error: expected primary-expression before ‘int’
test.cpp:7: error: expected ‘)’ before ‘int’
test.cpp:9: error: expected ‘)’ before ‘else’
test.cpp:13: error: expected primary-expression before ‘}’ token
test.cpp:13: error: expected ‘;’ before ‘}’ token

顺便说一句,我问的原因是因为这个答案:Seeing what class an object is

我试图找到一种使条件更具可读性的方法。通常情况下,我宁愿,例如:

if((x = y) != 0) { 

if(x = y) { 

...因为它更具可读性和沉默编译“意见”表明我可能使用了错误的操作。如果我使用声明作为条件,它不会产生警告,但可读性似乎仍然受到影响。

+2

你为什么要这么做任一? – 2010-12-13 09:11:08

+0

@Robin Welch - 用例和灵感来源于:http://stackoverflow.com/questions/4426476/seeing-what-c​​lass-an-object-is/4426485#4426485 – sje397 2010-12-13 09:14:55

回答

4

这是因为C++标准6.4 p1。

Selection statements choose one of several flows of control.

选择语句:

if (condition) statement 
if (condition) statement else statement 
switch (condition) statement 

条件:

expression 
type-specifier-seq declarator = assignment-expression 
+0

我已经添加了标准报价的开始。缺少的额外位是在“condition”的定义中它允许额外的括号,但不允许定义变量。 – 2010-12-13 10:05:33

3

这不是一项任务。这是一个声明。你可以把声明别处的条件下,如以下

if(int i = value) ...; 
for(...; int i = value; ...) ...; 
switch(int i = value) ...; 
while(int i = value) ...; 

这是一个很少使用的形式,但它是不是有指定的表达式。您所做的一切有声明一个变量i您可以在体内

// fire if get() returns non-null 
if(weapon *w = get()) { 
    w->fire(); 
} 

和括号不在身边这样的声明允许使用。我认为这没有意义。

+0

我应该补充,不要做这EVER。仅仅因为它在语法上正确并不意味着你的同行程序员会因为它而喜欢你。 – Neil 2010-12-13 09:15:20

+0

@Neil - 请参阅我的评论中的链接,以了解可能的原因。 – sje397 2010-12-13 09:17:47

+0

毫无疑问,您的链接显示了一个原因。虽然有更清晰的方法来做同样的事情,那为什么要牺牲简单性呢? – Neil 2010-12-13 09:30:01

相关问题