c++ - C++ 中初始化的结果是什么?

标签 c++ initialization

初始化的返回值是什么?例如: 在下面的代码中;

#include<iostream>

int main()
{
    int age = 30;          //does this statement return (thus; yield) anything?

    while(int i = 0){      //a similar statement (expression) used here in this condition
        std::cout<<"OK";   
    }

    return 0;
}
  • 语句 int Age = 27; 返回什么?
  • 当进行初始化(返回赋值运算符的左操作数)时,通常的赋值运算符含义是否适用?

我想知道这一点的原因是,当我们查看上面的条件语句时,我们会看到用作条件的变量的类似初始化。我知道无论返回什么值都会转换为 bool 类型。

注意:我并不想在 while 语句的条件下将 i 与 0 进行比较。

最佳答案

带有初始值设定项的声明语句只是声明语句,而不是表达式。它不会产生值。您不能执行类似 int x = (int n = 42); 的操作。

while 循环是一种特殊情况。您可以使用声明作为while循环的条件。根据cppreference.com ,

If this is a declaration, the initializer is evaluated before each iteration, and if the value of the declared variable converts to false, the loop is exited.

关于c++ - C++ 中初始化的结果是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59294508/

相关文章:

c++ - "fatal error: cg_config.h: No such file or directory"尝试使用 make 命令时出错

c++ - 如何将解决方案从 Visual Studio 2010 降级到 Visual Studio 2005?

c++ - vector <int> a 、 vector <int> a[n] 和 vector <int> a(n) 之间有什么区别?

java - 对象到底什么时候初始化的?

c++ - C++如何像Java Spring Assert一样检查条件并抛出异常

c++ - C++17 中 malloc 返回 "invalid pointer value"吗?

c++ - 虚幻引擎/C++ : How to draw a texture mask based on where 2D UI Widgets are on-screen

java - 在 Java 中初始化泛型

c++ - 如何使用预先计算的十六进制值初始化 double 组?

java - 将实例变量初始化为 null、 ""或 0