为什么这是正确的:宣布为条件 - 加括号会导致错误
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) {
...因为它更具可读性和沉默编译“意见”表明我可能使用了错误的操作。如果我使用声明作为条件,它不会产生警告,但可读性似乎仍然受到影响。
你为什么要这么做任一? – 2010-12-13 09:11:08
@Robin Welch - 用例和灵感来源于:http://stackoverflow.com/questions/4426476/seeing-what-class-an-object-is/4426485#4426485 – sje397 2010-12-13 09:14:55