Question: ```
void f(void);
int x = 15213;  
int main()  
{
    f();  
    printf("x = %d\n", x); 
    return 0; 
}

/* bar3.c */ 
int x; 
void f()
{ 
    x = 15212;
}

```

In the above code the output which i am getting is 15212. I dont understand how? 

First the main function calls f() define in another c file. In f() the value of x is changed to 15212 from 15213. And then we are printing x. But the change that has been made to x should remain in f only right? X should have its scope limited to f() only . Even then it is printing 15212

Answer: 
You've defined the variable `x` with *external* linkage in 2 translation units. The behaviour of the program is therefore **undefined**. [C11 6.9p5](http://port70.net/%7Ensz/c/c11/n1570.html#6.9p5):

> 
> 5. An external definition is an external declaration that is also a definition of a function (other than an inline definition) or an object. If an identifier declared with external linkage is used in an expression (other than as part of the operand of a sizeof or \_Alignof operator whose result is an integer constant), somewhere in the entire program there **shall be exactly one external definition** for the identifier; otherwise, there shall be no more than one.
> 
> 
> 

There is a common extension ([C11 J.5.11](http://port70.net/%7Ensz/c/c11/n1570.html#J.5.11)), that is present on **POSIX** systems (Unix, Mac OSX, Linux) that cause such external variable definitions to be **merged** into one:

> 
> J.5.11 Multiple external definitions
> 
> 
> 1. There may be more than one external definition for the identifier of an object, with or without the explicit use of the keyword extern; if the definitions disagree, or more than one is initialized, the behavior is undefined (6.9.2).
> 
> 
> 

However C compilers for other platforms need not necessarily follow this rule.

---

If you want both files to have separate variables named `x`, prefix each declaration with the keyword `static`, i.e. `static int x;`. If you want them to be portably one, use `int x;` **only in one file**, and `extern int x;` in all others; this `extern`al declaration can be put into a header file.
Because `x` is defined outside the scope of any function, it therefore has global scope. So the running of `f()` to assign its value actually changes its value as shown.

When `main()` runs the first thing it does is call `f()` which changes the value (some may argue as a side effect). That's why, the initialized value of 15213 is never used.