声明为条件-添加括号会导致错误 [英] declaration as condition - adding parentheses causes errors

查看:87
本文介绍了声明为条件-添加括号会导致错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么可以这样:

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:


test.cpp:7:错误:'int'之前的预期主表达式

test.cpp:7:错误:预期在'int'之前的


test.cpp:9:错误:预期在'else'之前的')'

test.cpp:13:错误:期望的主表达式在'}'令牌之前

test.cpp:13:错误:期望主表达式在'}'令牌之前

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

顺便说一句,我要问的原因是因为这个答案:查看对象是什么类

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.


选择语句选择几种控制流之一。

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

这篇关于声明为条件-添加括号会导致错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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