Home  >  Q&A  >  body text

c++ - 局部变量初始化的小问题

  局部未初始化内置类型变量在函数中一般是默认初始化(相对于全局变量),默认初始化的值都是未知值,但是g++下main函数中的这种类型变量会被初始化为0或空(如果是string或者是指针的话),但是vs下main函数中的这种类型变量会初始化为未知值,这是跟编译器有关的吗?

黄舟黄舟2714 days ago829

reply all(2)I'll reply

  • 怪我咯

    怪我咯2017-04-17 13:32:56

    As far as C language is concerned, local variables generally exist on the stack; unless it is some leaf function, a small number of local variables are placed directly in registers. The value in the stack is, of course, unknown by default. If the compiler generates a piece of code that specifically initializes local variables on the stack before referencing them, then it is similar to g++'s approach; otherwise, it is VS's approach.

    reply
    0
  • PHP中文网

    PHP中文网2017-04-17 13:32:56

    It should be yes, vs compiler, local built-in type variables are not initialized. C++ pursues higher performance. If it is not necessary, the C++ compiler will generally not do extra work, such as default initialization of variables. . .

    reply
    0
  • Cancelreply