Global vs. Local Variables

Global variables can be accessed and used by any function in a program. Local variables can be accessed only by the function in which they are defined. Both global and local variables are declared similarly in C, but they look completely different in assembly.

Following are two examples of C code for both global and local variables. Notice the subtle difference between the two. The global example, Example 6-1, defines x and y variables outside the function. In the local example, Example 6-2, the variables are defined within the function.

Example 6-1. A simple program with two global variables

int x = 1;
int y = 2;

void main()
{
   x = x+y;
   printf("total = %d\n", x);
}

Example 6-2. A simple program with two local variables

Get Practical Malware Analysis now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.