educative.io

Educative

C++ , why Pointer?

#include

int main() {

int i = 20;

int &iRef = i;

std::cout << "i: " << i << std::endl;

std::cout << "iRef: " << iRef << std::endl;

std::cout << std::endl;

iRef = 30; // Altering the reference

std::cout << "i: " << i << std::endl;

std::cout << "iRef: " << iRef << std::endl;

}
why is the result i = 20, iRef = 20 and i = 30, iRef = 30?

Hello @Emper_E,
This is because your variable iRef is pointing to the address of the variable i. So when you changed the value of iRef the value of i was also changed. Hope this helps.