Variables

When we are writing programs, we often want to manipulate values of various types. In order to do this C allows us to define storage locations for values. These locations are known as variables.

To define a variable, we normally use a declaration in the function where it is to be used. Variables may also be defined outside any function, allowing them to be used by several functions. Those inside a function are said to be local to the function where they are declared, since they cannot be used outside that function.

#include 

  /*This is an even less simple program */
int main(int argc, char *argv[])
{
    int CharVal;
    CharVal = getchar();
    if (CharVal=='a') printf("%s Success\n",argv[1]); 
                 else printf("Failure\n");
    return EXIT_SUCCESS;
}
Plain text version to compile.

Here we see an example of a variable called CharVal which is declared inside the main program function, main(). It is declared following a keyword, int in this case, which specifies what type of value it can hold.

Variables declared outside any function can be used anywhere following their declaration in the program, since this level contains all functions in the program. Since the whole world can see them, variables declared at this level are often called global variables. The use of global variables is dealt with in a later section.


Exercises on this section.


Next.

Back to Contents page.