c - What happens if i declared another variable with the same name in another file? -
i have declared int x in file one , mistake declared variable of type char same name x in file two, , wait compiler or linker give me error, there no errors displayed. , when use debugger see int x converted char x , true?! , happens here?!
show modification on code:
file one
#include <stdio.h> int x = 50; /** declare global variable called x **/ int main() { print(); printf(" global in file 1 = %d",x); /** modification here **/ return 0; } file two
char x; void print(void) { x = 100; printf("global in file 2 = %d ",x); return; } my expected results = global in file 2 = 100 global in file 1 = 50
but results : global in file 2 = 100 global in file 1 = 100
when use debugger see int x converted char x , true?! , happens here?
you're in troublesome territory here. technically program causes undefined behaviour. char x tentative definition, since doesn't have initializer. means linker unifies int x in other file @ link time. it's bit weird looking, since 2 declarations have different types, appears have linked in case. anyway, have 1 x, , luck making work way you're seeing (and little-endian architecture, probably).
if want 2 variables independent, make them static, , they'll restricted scope of respective translation units.
Comments
Post a Comment