Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does initializing a variable `i` to 0 and to a large size result in the same size of the program?

Tags:

c

variables

size

There is a problem which confuses me a lot.

int main(int argc, char *argv[])
{
    int i = 12345678;
    return 0;
}

int main(int argc, char *argv[])
{
    int i = 0;
    return 0;
}

size

The programs have the same bytes in total. Why?

And where the literal value indeed stored? Text segment or other place?

memory map

like image 450
MiterV Avatar asked Oct 20 '15 15:10

MiterV


People also ask

What do you understand by initialization of a variable?

Initializing a variable means specifying an initial value to assign to it (i.e., before it is used at all). Notice that a variable that is not initialized does not have a defined value, hence it cannot be used until it is assigned such a value.

What will be the value of a global variable that declared but not initialized?

I learned that if variables are declared but not assigned any value they are initialized with a random value (except static and global variables which are initialized with 0).

How many variables can be initialized at a time?

You can initialize as many as you want of any type, but should you use an inline declaration, all declared variables must be of the same type, as pst sort of mentioned.

Can a programmer have multiple initializations in an initialization box?

No, you can only have one initializing statement.


1 Answers

The programs have the same bytes in total.Why?

There are two possibilities:

  1. The compiler is optimizing out the variable. It isn't used anywhere and therefore doesn't make sense.

  2. If 1. doesn't apply, the program sizes are equal anyway. Why shouldn't they? 0 is just as large in size as 12345678. Two variables of type T occupy the same size in memory.

And where the literal value indeed stored?

On the stack. Local variables are commonly stored on the stack.

like image 145
cadaniluk Avatar answered Sep 22 '22 19:09

cadaniluk