C Programming Absolute Beginner's Guide (3rd Edition)

(Romina) #1
opening braces. Some statements, such as while, also have opening braces, and you can define
local variables within those braces as well.

Tip

An opening and closing brace enclose what is known as a block.

Given these rules, it should be obvious that l1 and l2 are local variables and that g1 and g2 are
global variables in the following program:


Click here to view code image


// Example program #1 from Chapter 30 of Absolute Beginner's Guide
// to C, 3rd Edition
// File Chapter30ex1.c
/* The program is a simple demonstration of the difference between
global variables and local variables. */
#include <stdio.h>
int g1 = 10;
main()
{
float l1;
l1 = 9.0;
printf("%d %.2f\n", g1, l1); // prints the 1st global and first
// local variable
prAgain(); // calls our first function
return 0;
}
float g2 = 19.0;
prAgain()
{
int l2 = 5;
// Can't print l1--it is local to main
printf("%d %.2f %d\n", l2, g2, g1);
return;
}

Tip

You might not yet completely understand the return 0; statement. To make matters
worse, return by itself is used at the end of the prAgain() function. You’ll find a
detailed description for return in the next two chapters.
Free download pdf