Global Variables in C

Posted By on September 27, 2016


Download PDF
C Program Structure
Order of Precedence in C

Global variables are defined above main() in the following way:-


          short number,sum;
		 int bignumber,bigsum;
		 char letter;
 
		 main()
				 {
 
				 }

It is also possible to pre-initialise global variables using the = operator for assignment.

NOTE: The = operator is the same as := is Pascal.

For example:-


          float sum=0.0;
		 int bigsum=0;
		 char letter=`A';
 
		 main()
				 {
 
				 }

This is the same as:-


          float sum;
		 int bigsum;
		 char letter;
 
		 main()
				 {
 
				 sum=0.0;
				 bigsum=0;
				 letter=`A';
 
				 }

…but is more efficient.

C also allows multiple assignment statements using =, for example:


          a=b=c=d=3;

…which is the same as, but more efficient than:


          a=3;
		b=3;
		c=3;
		d=3;

This kind of assignment is only possible if all the variable types in the statement are the same.

You can define your own types use typedef. This will have greater relevance later in the course when we learn how to create more complex data structures.

As an example of a simple use let us consider how we may define two new types real and letter. These new types can then be used in the same way as the pre-defined C types:


          typedef real float;
		 typedef letter char;
 
Variables declared:
		 real sum=0.0;
		 letter nextletter;

Printing Out and Inputting Variables

C uses formatted output. The printf function has a special formatting character (%) — a character following this defines a certain format for a variable:


    %c -- characters
		 %d -- integers
		 %f -- floats

e.g. printf("%c %d %f",ch,i,x);

NOTE: Format statement enclosed in “…”, variables follow after. Make sure order of format and variable data types match up.

scanf() is the function for inputting values to a data structure: Its format is similar to printf:

i.e. scanf("%c %d %f",&ch,&i,&x);

 

C Program Structure
Order of Precedence in C

Download PDF

Posted by Akash Kurup

Founder and C.E.O, World4Engineers Educationist and Entrepreneur by passion. Orator and blogger by hobby

Website: http://world4engineers.com