C ++ 17 if语句带有初始化但无条件 [英] C++17 if statement with initializer but no condition

查看:102
本文介绍了C ++ 17 if语句带有初始化但无条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在c ++ 17中,您可以执行以下操作:

In c++17 you can do the following:

if ( init-statement(optional); condition )

根据 https://en.cppreference.com/w/cpp/language/if

但是我的编译器( vs2019)允许

However my compiler (vs2019) allows

if ( init-statement )

其中初始化语句也是条件。我找不到它记录在任何地方,实际上可以保证吗?

where the init-statement is also the condition. I can't find that this is documented anywhere, is this actually guaranteed to work?

推荐答案

在C ++中,很多事情可以进入条件,而您不会期望在那里。例如,条件可以是 int i = 20 int i = 20 解析为一个可以在上下文中转换为布尔值并经过测试的值。

In C++, a lot of things can go into condition that you wouldn't expect to be allowed there. A condition for example can be int i = 20. int i = 20 resolves to a value which can be contextually converted into a boolean and tested.

所以不是您的编译器允许初始语句而没有条件。从一开始,就是C ++允许条件语法包括声明变量,而您的代码只是在使用它。

So it's not that your compiler is allowing an init-statement without a condition. It's that C++ since the beginning has allowed condition grammar to include declaring a variable, and your code is simply using that.

这篇关于C ++ 17 if语句带有初始化但无条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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