Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the compiler allow initializing a variable with itself? [duplicate]

Tags:

c

I finally trace down a typo bug, which is something similar to the following code. But shouldn't the compiler detect this (by default options)?

#include <stdio.h>

int main()
{
    int c = c;
    return printf("%d\n", c);
}


$ gcc --version        
gcc (Ubuntu 4.4.3-4ubuntu5.1) 4.4.3
like image 886
user180574 Avatar asked Apr 19 '13 17:04

user180574


People also ask

What purpose does initializing a variable serve?

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.

Why is it important to always initialize variables when you declare them?

To declare a variable that has been initialized in another file, the keyword extern is always used. By always initializing variables, instead of assigning values to them before they are first used, the code is made more efficient since no temporary objects are created for the initialization.

Are variables in C automatically initialized?

There's no automatic initialization of automatic ( local in your parlance) variables in C.

Why is it important to always initialize your variables in AC program?

Initializing a variable as Telastyn pointed out can prevent bugs. If the variable is a reference type, initializing it can prevent null reference errors down the line. A variable of any type that has a non null default will take up some memory to store the default value.


1 Answers

I don't see why it wouldn't compile. Definition happens prior to initialization. Of course this initialization is pointless, however, there's no reason it wouldn't work from the compilers stand point.

C does not have the same types of protections that more modern languages like C# have. The C# compiler would give an error that you're using an unassigned variable. C doesn't care. It will not protect you from yourself.

like image 52
evanmcdonnal Avatar answered Oct 09 '22 06:10

evanmcdonnal