Sharon
Sharon

Reputation: 171

global definition of a variable in C

In simple terms global variables are variables that are declared or defined outside main() and has scope from the point of definition to the end of the program.

I have a few questions on global variables. I am using GCC compiler.

#include<stdio.h>
int a,b;
a=b=1;
main()
{
     printf("%d\n%d",a,b);
}

This program generates error while

#include<stdio.h>
int a,b;

main()
{
     a=b=1;
     printf("%d\n%d",a,b);
}

generates the correct output.Why a=b=1 is not supported when used globally?

I have one more question to ask.

#include<stdio.h>
a=1;
b=9;
c='c';
h='h';

main()
{
    printf("%d\n%d\n",a,b);
    printf("%c\t%c\n",c,h);

}

produces the correct result with warning that data definition has no type or storage class. I am totally confused with global variables.

Upvotes: 2

Views: 1889

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409472

The line

a=b=1;

is a statement, and in the global scope you can't have statements, only declarations and definitions.

When you do

a=1;

you implicitly define the variable a as an int and then initialize it to the value 1. This can only be done in the global scope, but don't do it as it's going to cause a lot of confusion.

Upvotes: 2

Related Questions