Total Pageviews

Tuesday, 1 May 2012

C Variables

Defining Global Variables
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;

No comments:

Post a Comment