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
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.
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.
There's no automatic initialization of automatic ( local in your parlance) variables in C.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With