增加非初始化变量是否合法? [英] Is it legal to increment non-initialized variable?

查看:87
本文介绍了增加非初始化变量是否合法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int main() {
 int i;
 i++; // 1
}

我可以确定我总是获得值1后使用增量?因为我经常听到一个变量可以包含任何东西在初始化之前。所以这是非法的?

Can I be sure that I always get the value "1" after using increment? Because I often hear that a variable can contain anything before initializing. So it's illegal? Or increment always starts from "0" if the variable is a non-initialized?

推荐答案


如果变量是非初始化的,没有为一个对象指定初始化器,该对象被默认初始化。当获得具有自动或动态存储持续时间的对象
的存储时,对象具有不确定的值,并且如果
没有对对象执行初始化,则该对象保持不确定的值直到该值为
替换

If no initializer is specified for an object, the object is default-initialized. When storage for an object with automatic or dynamic storage duration is obtained, the object has an indeterminate value, and if no initialization is performed for the object, that object retains an indeterminate value until that value is replaced

整数的默认初始化是无操作的,这意味着不执行初始化。这意味着你的示例中的 i 有一个不确定的值。使用该对象,就像它有一个值导致未定义的行为:

Default-initialization for integers is a no-op, meaning no initialization is performed. That means i in your example has an indeterminate value. Using the object as if it had a value results in undefined behavior:


如果一个不确定的值是由评估产生的,行为是未定义的[..]

If an indeterminate value is produced by an evaluation, the behavior is undefined [..]

这篇关于增加非初始化变量是否合法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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