views:

31

answers:

3

Given the files:

// file: q7a.h
static int err_code = 3;
void printErrCode ();
///////////// END OF FILE /////////////////
// file: q7a.c
#include <stdio.h>
#include "q7a.h"
void printErrCode ()
{
printf ("%d ", err_code);
}
///////////// END OF FILE /////////////////
// file: q7main.c
#include "q7a.h"
int main()
{
err_code = 5;
printErrCode ();
return 0;
}
///////////// END OF FILE /////////////////

The output is:

3

My Question is why the output is not 5? Thanks.

+4  A: 

static global objects have scope limited to the current compilation unit. In this case you have two compilation units, one for each .c file, and each one has its own err_code.

ninjalj
+3  A: 

The static keyword for err_code specifies static linkage, i.e. the variable is local to the translation unit.

As you're compiling files q7a.c and q7main.c separately, there will be two different err_code variables. Hence the function printErrCode in q7a.c is using err_code visible only within the q7a.c scope.

Schedler
A: 

The output is not 5, because global variables are bad.

Try this, without declaring err_code anywhere and replacing the call in main():

void printErrCode (int err_code)
{
    printf ("%d ", err_code);
}

int main ()
{
    /* ... */
    printErrCode(5);
    /* ... */
}
pmg