Nikhil kumar
Nikhil kumar

Reputation: 161

How compile time initialization of variables works internally in c?

Is compile time initialization only happens when we give value to the variable during variable declaration. To be more specific, What is the difference between initializing variable during declaration int a=2 and after declaration int a; a=2?

Upvotes: 6

Views: 1901

Answers (2)

klutt
klutt

Reputation: 31306

What is the difference between initializing variable during declaration int a=2 and after declaration int a; a=2?

The difference is that the second one is not an initialization. It's an assignment. When it comes to your very simple example, there is no difference in practice.

structs and arrays

A big difference is that some initialization tricks are not available on regular assignments. Like for instance array and struct initialization. You'll need C99 or higher.

int x[5] = {1, 2, 3, 4, 5}; // Ok
x = {1, 2, 3, 4, 5};        // Not ok

struct myStruct {
    int x;
    char y;
};

struct myStruct a = {1, 'e'};     // Ok
a = {1, 'e'};                     // Not ok
a = (struct myStruct) {1, 'e'};   // But this is ok
struct myStruct b = {.y = 'e'};   // Also ok
b = (struct myStruct) {.y = 'e'}; // Even this is ok
b = {.y = 'e'};                   // But not this

You can assign arrays with a little trick. You wrap the array in a struct. However, I would not recommend this for this purpose. It's not worth it.

struct myArrayWrapper {
    char arr[5];
};

struct myArrayWrapper arr;
arr = (struct myArrayWrapper) {{1,2,3,4,5}}; // Actually legal, but most people
                                             // would consider this bad practice 

constant variables

And if you have declared a variable as const then you cannot change it later, so they "have" to be initialized.

const int x = 5; // Ok
x = 3; // Not ok, x is declared as const
const int y;     // "Ok". No syntax error, but using the variable is 
                 // undefined behavior
int z = y;       // Not ok. It's undefined behavior, because y's value
                 // is indeterminate

Constant variables are not strictly required to be initialized, but if you don't, they become completely worthless.

static variables

It also affects static variables in a special way.

void foo() {
    static int x = 5; // The initialization will only be performed once
    x = 8;            // Will be performed everytime the fuction is called

So this function will return 1 if it has been called before and 0 otherwise:

int hasBeenCalled() {
    static int ret = 0;
    if(!ret) {
        ret = 1;
        return 0;
    }
    return 1;
}

Another thing about static variables is that if they are not explicitly initialized, they will be initialized to zeros. Local variables (variables with automatic storage) will contain garbage values. Also, do note that global variables are automatically static.

static int x; // Will be initialized to 0 because it's static
int y;        // Is also static, because it's global
auto int z;   // Not ok. You cannot declare auto variables in global space

int main(void)
{
    int a;        // Will be auto as b
    auto int b;   
    static int c; 
    
    int d;
    d = a;        // Not ok because b is not initialized.
    d = b;        // Not ok
    d = c;        // Ok because static variables are initialized to zero
    d = x;        // Ok
    d = y;        // Ok

In practice, you NEVER use the auto keyword in C. Actually, there are no situations where auto is legal to use where it would not default to auto if you omit it. That's not true for static.

You can read about initialization in chapter 6.7.9 in the C standard. Assignments are found in chapter 6.5.16

Upvotes: 6

the busybee
the busybee

Reputation: 12600

The standard defines no compile time initialization. It depends on the environment your code is developed and run on.

How variables are initialized depends on their storage duration. You didn't mention it.

Initialized automatic variables will be written each time their declaration is reached. So the split version you show will make no difference.

Static variables are always intialized and only once before the program startup. So your split version is not an initialization and it is done every time the assignment is reached.

Examples from the real world:

Most (if not all) PC systems store the initial values of explicitly (and not zero-) initialized static variables in a special section called data that is loaded by the system's loader to RAM. That way those variables get their values before the program startup. Static variables not explicitly initialized or with zero-like values are placed in a section bss and are filled with zeroes by the startup code before program startup.

Many embedded systems have their program in non-volatile memory that can't be changed. On such systems the startup code copies the initial values of the section data into its allocated space in RAM, producing a similar result. The same startup code zeroes also the section bss.

Note 1: The sections don't have to be named liked this. But it is common.

Note 2: There are more kinds of storage duration, please see chapter 6.2.4 of the standard.

As long as the standard is met, a system is free to implement any other kind of initialization, including writing the initial values into their variables step by step.

Upvotes: 2

Related Questions