Search code examples
c++stackcalling-convention

cout value without touching variable C++


When I run the program, it prints the value of variable a. But when I comment the line 'cout<<&b<<endl<<&a<<endl;' it prints a garbage value. What can be the explanation behind it?

#include<iostream>
using namespace std;

int main()
{
    int a = 9;
    int b = 10;
    int *pb = &b;
    cout<<&b<<endl<<&a<<endl;
    cout<<*(pb+1);
}

Solution

  • When you print the addresses of a and b, that forces the variables to actually have a memory address. Otherwise a value might be stored in a register, or not at all if never used.

    It is a very common optimization for compilers to transform

    const int a = 9;
    cout << a;
    

    into

    cout << 9;
    

    and never store a anywhere.

    And anyway, there are no rules saying where and in what order the variables are to be stored in memory. That is totally up to the compiler. So your assumption that &a == &b + 1 (or &b - 1) is not valid.