简体   繁体   English

一些基本的C ++概念-初始化和赋值

[英]Some basic C++ concepts — initialization and assignment

I was asked in an interview, to tell the exact difference for the following c/c++ code statements 我在一次采访中被要求说出以下c / c ++代码语句的确切区别

int a = 10;

and

int a;
a = 10;

Though both assign the same value, they told me there is a lot of difference between the two in memory. 尽管两者都分配了相同的值,但他们告诉我两者在内存中存在很大差异。

Can anyone please explain to me about this? 有人可以向我解释一下吗?

As far as language concerned, they are two ways to do the same thing, initialize the variable a and assign 10 to it. 就语言而言,它们是完成相同操作的两种方法, 初始化变量a为其分配 10。

The statement int a; 声明int a; reserves memory for the value a which certainly contains garbage. 为肯定包含垃圾的值a 保留内存

Because of that you initialize it with a = 10; 因此,您初始化a = 10;

In the statement int a = 10; 在语句中in int a = 10; these two steps are done in the same statement. 这两个步骤在一条语句中完成。

First a part of memory is reserved to the variable a , and then the memory is overwritten with the value of 10 . 首先,将内存的一部分保留给变量a ,然后用值10 覆盖内存。

int a                                     =  10;
^^^^^                                     ^^^^^
reserve memory for the variable a         write 10 to that memory location

Regarding memory the first declaration uses less memory on your PC because less characters are used, so your .c file will be smaller. 关于内存,第一个声明在PC上使用的内存较少,因为使用的字符较少,因此.c文件将更小。

But after compilation the produced executable files will be the same . 但是,编译后生成的可执行文件将相同

IMPORTANT : if those statements are outside any function they are possibly not the same (although they will produce the same result). 重要说明 :如果这些语句在任何函数之外,则它们可能不相同(尽管它们将产生相同的结果)。

The problem is that the first statement will assign 0 to a in the first statement because most compilers do that to global variables in C (and is defined by C standard). 问题在于,第一条语句将为第一条语句中的a分配0 ,因为大多数编译器都将其赋给C中的全局变量(由C标准定义)。

"Though both assign the same value, but there is a lot of difference between the two in memory." “尽管两者都分配了相同的值,但是两者在内存中存在很大差异。”

No, there's no difference in stack memory usage! 不,堆栈内存使用率没有差异!
The difference is that assigning a value though initialization may cause some extra cost for additional assembler instructions (and thus memory needed to store it, aka. code footprint ), the compiler can't optimize out at this point (because it's demanded). 区别在于通过初始化分配值可能会导致额外的汇编器指令(以及因此需要存储的内存,即代码占用空间 )带来一些额外成本,编译器此时无法优化(因为这是必需的)。

If you initialize a immediately this will have some cost in code. 如果立即初始化a ,这将花费一些代码。 You might want to delay initialization for later use, when the value of a is actually needed: 当实际需要a的值时,您可能希望延迟初始化以供以后使用:

void foo(int x) {
    int a; // int a = 30; may generate unwanted extra assembler instructions!

    switch(x) {
    case 0:
        a = 10;
        break;
    case 1:
        a = 20;
        break;
    default:
        return;
    }

    // Do something with a correctly initialized a
}

This could have well been an interview question made to you in our company, by particular colleagues of mine. 这很可能是我公司的某些同事在我们公司向您提出的面试问题。 And they'd wanted you to answer, that just having the declaration for int a; 他们想让您回答,只是有int a;的声明int a; in 1st place is the more efficient choice. 在第一名是更有效的选择。

I'd say this interview question was made to see, if you're really have an in-depth understanding of c and c++ language (A mean-spirited though!). 我想说这个面试问题是要看您是否真的对c和c ++语言有深入的了解(尽管很卑鄙!)。


Speaking for me personally, I'm more convenient on interviews about such stuff usually. 就我个人而言,通常在采访中我会更方便。

I consider the effect is just very minimal. 我认为效果只是很小。 Though it could well seriously matter on embedded MCU targets, where you have very limited space left for the code footprint (say less/equal than 256K), and/or need to use compiler toolchains that actually aren't able to optimize this out for themselves. 虽然这对于嵌入式MCU目标可能非常重要,但您的代码足迹空间却非常有限(例如小于/等于256K),并且/或者需要使用编译器工具链,而这些工具链实际上无法对其进行优化他们自己。

If you are talking about a global variable (one that doesn't appear in a block of code, but outside of all functions/methods): 如果您正在谈论一个全局变量(一个不在代码块中但在所有函数/方法之外的变量):

int a;

makes a zero-initialized variable. 产生一个零初始化的变量。 Some (most?) c++ implementations will place this variable in a memory place (segment? section? whatever it is called) dedicated for zero-initialized variables. 一些(大多数?)c ++实现会将此变量放置在专用于零初始化变量的内存位置(段?节?无论它叫什么)。

int a = 10;

makes a variable initialized to something other than 0. Some implementations have a different region in memory for these. 使变量初始化为非0的值。某些实现在这些存储器中具有不同的区域。 So this variable may have an address ( &a ) that is very different from the previous case. 因此,此变量的地址( &a )与前一种情况非常不同。

This is, I guess, what you mean by "lot of difference between the two in memory". 我猜,这就是“内存中两者之间的差异很大”的意思。

Practically, this can affect your program if it has severe bugs (memory overruns) - they may get masked if a is defined in one manner or the other. 实际上,如果程序存在严重的错误(内存溢出),这可能会影响您的程序-如果以一种或另一种方式定义a它们可能会被掩盖。

PS To make it clear, I am only talking about global variables here. PS为了明确起见,我在这里仅谈论全局变量。 So if your code is like int main() {int a; a = 10;} 因此,如果您的代码类似于int main() {int a; a = 10;} int main() {int a; a = 10;} - here a is typically allocated on stack and there is no "difference in memory" between initialization and assignment. int main() {int a; a = 10;} -这里的a通常分配在堆栈上,初始化和赋值之间没有“内存差异”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM