C ++中的变量初始化 [英] Variable initialization in C++

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

问题描述

我的理解是 int 变量会自动初始化为 0 然而,它不是。下面的代码打印一个随机值;任何人都可以告诉我什么规则,如果有的话,适用于初始化?具体来说,在什么条件下自动初始化变量?

My understanding is that the int variable will be initialized to 0 automatically; however, it's not. The code below prints a random value; can anybody tell me what rules, if any, apply to initialization? Specifically, under what conditions are variable initialized automatically?

int main () 
{   
    int a[10];
    int i;
    cout << i << endl;
    for(int i = 0; i< 10; i++)
        cout << a[i] << " ";
    return 0;
}


推荐答案


  • 它是一个类/结构实例,默认构造函数初始化所有基本类型; MyClass实例;

  • 您使用数组初始化语法,例如。 int a [10] = {} (全零)或 int a [10] = {1,2}; a [0] == 1 a [1] == 2

  • 同样适用于非聚合类/结构体,例如MyClass instance = {}; (有关此问题的详情,请访问这里

  • 它是一个全局/外部变量

  • 定义变量 static

  • it's a class/struct instance in which the default constructor initializes all primitive types; like MyClass instance;
  • you use array initializer syntax, e.g. int a[10] = {} (all zeroed) or int a[10] = {1,2}; (all zeroed except the first two items: a[0] == 1 and a[1] == 2)
  • same applies to non-aggregate classes/structs, e.g. MyClass instance = {}; (more information on this can be found here)
  • it's a global/extern variable
  • the variable is defined static (no matter if inside a function or in global/namespace scope) - thanks Jerry

不要信任一个简单类型(int,long,...)的变量被自动初始化!它可能发生在像C#的语言,但不是在C& C ++。

Never trust on a variable of a plain type (int, long, ...) being automatically initialized! It might happen in languages like C#, but not in C & C++.

这篇关于C ++中的变量初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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