Is scope in C related only to compile time, as we know we can access any memory at run time? -


i trying understand exact meaning of scope in c. understand scope limited compile time only. example, in case access local variable other function. result in compile time error. on other hand, following program works fine. means c has flat memory model , can accessed @ run time. c books associate scope lifetime , variable visibility, found quite confusing. think these terms makes sense compile time. can please throw light on it?

#include "stdio.h"  int *ptr;  int func(void) {   /** abc local variable **/   int abc = 132;   ptr = &abc;   return 0; }  int func1(void) {    /** although scope of abc on still can change value in address  of abc **/   *ptr = 200;   printf("the value of abc=%d\r\n",*ptr);  }  int main(void) {    func();    func1();    return 0; } 

results: value of abc=200

in simpler words, meant scope? come picture @ run time or compile time? can see, can access @ run-time. but, if don't follow rules, compilation error. example, local variable reference in function. compiler throw error saying, "variable not defined...".

can following variables?

1) scope attribute comes under compile time. 2) lifetime attribute comes under run-time. 3) visibility attribute comes under compile-time 

yes, c's memory model allows access can things above , see "interesting" results.

however, did here specified undefined behavior (ub) c standard. means literally can happen; might expect, or might not.

note did not access "the local variable" because time make access func has returned, lifetime of local variables has expired. did access memory region "just happened" have interesting value. if called func1 inside func behavior well-defined.

a few more notes:

scope compile-time-only concept; scope of name (variable, identifier, etc) subset of program code name recognized compiler.

this different lifetime of variables, independent of scope in general case, , conflating 2 common mistake. lifetime , scope of local variables indeed intertwined, that's not true of everything.


Comments

Popular posts from this blog

html - How to style widget with post count different than without post count -

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

javascript - storing input from prompt in array and displaying the array -