gpt4 book ai didi

c++ - 为什么 int x{ y = 5 } 可能?

转载 作者:行者123 更新时间:2023-12-02 00:47:04 26 4
gpt4 key购买 nike

int main() {
int y;
int x{ y = 5 };
//x is 5
}

这怎么可能,因为 y = 5 不是一个可计算的表达式?

另外,为什么编译器或 IDE 不会提示 main() 没有返回 int?

最佳答案

How is this possible, since y = 5 is not a calculable expression?

这是一个赋值,赋值会产生值,即“左操作数的 cv 限定类型”,请参阅 [expr.ass/3] 。因此,y = 5 结果为 y,即 5,用于初始化 x

关于你的第二个问题,请参阅 main 上的 cppreference (或[basic.start.main/5]):

The body of the main function does not need to contain the return statement: if control reaches the end of main without encountering a return statement, the effect is that of executing return 0;.

因此,编译器或 IDE 警告您 main 末尾缺少 return 语句将是完全错误的。诚然,您应该始终从非 void 函数返回对象execpt main这一事实是...... .好吧,我猜是出于历史原因。

关于c++ - 为什么 int x{ y = 5 } 可能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58447726/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com