albin
albin

Reputation: 783

Why local variables do not have default type while global variables have in C?

As far as I know global variables in C have int type as default. I just wonder the rational behind why local (auto) variables has no default type and the code below results compilation error

int main(int argc, char *argv[])
{
    x;
    return x;
}

while this does not?

x;
int main(int argc, char *argv[])
{

    return x;
}

Upvotes: 2

Views: 90

Answers (2)

ouah
ouah

Reputation: 145829

The rule for the implicit int is no longer allowed since c99.

However for local variables (your first example) even this was not allowed as a declaration:

x;  /* or even x = 42; */

because it was ambiguous. Is this an expression statement that evaluates x or a declaration of x? In the file scope statements are not allowed so there is no ambiguity and it can only be a declaration of an int.

Upvotes: 4

Shoe
Shoe

Reputation: 76240

An object name in the global namespace can only mean object declaration/definition. In a local namespace x; could also mean "simply do nothing with the already initialised object x".

Upvotes: 3

Related Questions