在if的条件中声明一个变量有什么问题? [英] what's wrong with declaring a variable inside if's condition?

查看:552
本文介绍了在if的条件中声明一个变量有什么问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

也许我变得生锈了(最近一直在写Python)。

Perhaps I am getting rusty (have been writing in Python recently).

为什么不编译?

if ( (int i=f()) == 0)

code> int i = f()我得到另一个更合理的错误: i 不是布尔。但是这就是为什么我想要的括号在第一个地方!

without the () around the int i=f() I get another, much more reasonable error of i is not being boolean. But that's why I wanted the parentheses in the first place!

我的猜测是,使用括号使它成为一个表达式,声明语句不允许在表达。是这样吗?如果是,是C ++的语法quirks之一?

My guess would be that using the parentheses makes it into an expression, and that declaration statements are not allowed in an expression. Is it so? And if yes, is it one of the C++'s syntax quirks?

BTW,我其实是试图这样做:

BTW, I was actually trying to do this:

if ( (Mymap::iterator it = m.find(name)) != m.end())
    return it->second;


推荐答案

您可以在 if 语句在C ++中,但它只能用于直接初始化,并且需要转换为布尔值:

You can declare a variable in the if statement in C++ but it is restricted to be used with direct initialization and it needs to convert to a Boolean value:

if (int i = f()) { ... }

C ++没有什么可以被描述为声明表达式,即[子]表达式声明一个变量。

C++ doesn't have anything which could be described as "declaration expression", i.e. [sub-] expressions declaring a variable.

其实,我只是查找了子句根据6.4 [stmt.select]段落1支持标准和两种形式的初始化:

Actually, I just looked up the clause in the standard and both forms of initialization are supported according to 6.4 [stmt.select] paragraph 1:

...
condition:
   expression
   attribute-specifier-seqopt decl-specifier-seq declarator = initializer-clause
   attribute-specifier-seqopt decl-specifier-seq declarator braced-init-list
...

也就是说,也可以这样写:

That is, it is also be possible to write:

if (int i{f()}) { ... }

显然,这只适用于C ++ 2011,因为C ++ 2003没有括号初始化。

Obviously, this only works in C++2011 because C++2003 doesn't have brace-initialization.

这篇关于在if的条件中声明一个变量有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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