Defining a variable in the condition part of an if-statement?(在 if 语句的条件部分定义变量?)
问题描述
我很震惊,这是允许的:
I was just shocked, that this is allowed:
if( int* x = new int( 20 ) )
{
std::cout << *x << "!
";
// delete x;
}
else
{
std::cout << *x << "!!!
";
// delete x;
}
// std:cout << *x; // error - x is not defined in this scope
那么,这是标准允许的还是只是编译器扩展?
So, is this allowed by the standard or it's just a compiler extension?
P.S.因为有几个关于这个的评论 - 请忽略这个例子是坏的"或危险的.我知道什么.举个例子,这只是我想到的第一件事.
P.S. As there were several comments about this - please ignore that this example is "bad" or dangerous. I know what. This is just the first thing, that came to my mind, as an example.
推荐答案
这是规范允许的,因为 C++98.
This is allowed by the specification, since C++98.
来自第 6.4 节选择声明":
From Section 6.4 "Selection statements":
由条件中的声明引入的名称(由类型说明符序列或条件的声明符引入)的范围从其声明点到由条件控制的子语句结束.
A name introduced by a declaration in a condition (either introduced by the type-specifier-seq or the declarator of the condition) is in scope from its point of declaration until the end of the substatements controlled by the condition.
以下示例来自同一部分:
The following example is from the same section:
if (int x = f()) {
int x; // ill-formed, redeclaration of x
}
else {
int x; // ill-formed, redeclaration of x
}
这篇关于在 if 语句的条件部分定义变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 if 语句的条件部分定义变量?
基础教程推荐
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07