declaration - declare extern variable within a C function? -
i define variable in c file: int x
, , know should use extern int x
declare in other files if want use in other files.
my question is: should declare in other files?
outside of functions,
// in file a.c: int x; // in file b.c: extern int x; void foo() { printf("%d\n", x); }
within function(s) use it?
// in file b.c: void foo() { extern int x; printf("%d\n", x); }
my doubts are:
- which 1 correct?, or
- which preferred if both correct?
both correct.
which 1 preferred depend on scope of variable's use.
if use in 1 function, declare in function.
void foo() { extern int x; <--only used in function. printf("%d",x); }
if used more 1 function in file, declare global value.
extern int x; <-- used in more 1 function in file void foo() { printf("in func1 :%d",x); } void foo1() { printf("in func2 :%d",x); }
Comments
Post a Comment