Search code examples
c++variables

why is the variable of a subroutine is accesing the value of another subroutine?


code sample

Why is the value of 'a' being printed for variable 'b' ? Acc. to what i understand variable of subroutines are stack-dynamic-variables and memory cells for subroutines are allocated when the subroutine begins execution, and are de-allocated when the subroutine ends execution.(Took this info from - https://cse.buffalo.edu/~shapiro/Courses/CSE305/Notes/notes6.html) Please tell me if am wrong.

using namespace std;    
    void a(){
      int a = 743;
      cout<<a<<endl;
    }
    void b() {
      int b;
      cout<<b<<endl;
    
    int main() {
      a();
      b();
      return 0;
    }

Solution

  • It's because you're not initialising b in your second function, meaning it will have some arbitrary value. The value that it's getting in this case appears to be the value of a from the previous function.

    When you call a function, it adjusts the stack pointer so that it has a stack frame separate from the caller main(). Calling a() does that and it will then set some memory location (for the local variable a) in its stack frame to be 743.

    When we then exit a(), we adjust the stack pointers so that we are once again using the stack frame of main() but we do not clear out the memory where the a() stack frame was.

    Then, on calling b(), we adjust the stack frame and, given the similarity between the two functions (same number of parameters, same number of local variables, etc), the memory location of b just happens to be where a was when a() was executing.

    That's why it has the same value.

    Keep in mind this is only due to the particular scenario you have and is in no way guaranteed by the standard. The instant you used b without first initialising it, you were guaranteed to get some arbitrary value.

    Bottom line, initialise your variables before you attempt to use them.