Search code examples
cmemoryglobal-variablesredefinition

Why Global variable redefinition is not allowed?


#include<stdio.h>

int i =0;
i=2;

int main(){

    // some Code here
    return 0;
}

Error : /Users/vaibhavkumar/Documents/C/primeFactors.c|4|error: redefinition of 'i'|

  1. Why redefinition of the variable is not allowed in C.
  2. Global variables are stored in Data Segment(area of memory), at the same place where static variables are stored. How came static variables can be redeclared ?

Solution

  • That is not redefinition it is assignment.

    Assignment is not the same as initialisation in C, and cannot be done outside a function - there is no thread of execution in that context, so when would it be done?

    Variables with static linkage are no different to global variables (with extern linkage) in this respect, however static linkage variables are local to a single compilation unit and are not visible externally. If you declare two statics of the same name in separate compilation units, they are entirely independent and unrelated variables - they needn't even be the same type.

    Note that static linkage is distinct from static storage, but they use the same keyword. All global and static linkage variables have static storage class implicitly, but a function local variable declared static has static storage class - i.e. it always exists - like a global, but is only visible locally.