Saturday, April 19, 2025

C++ References

Think about a reference as aliase for a variable. To have a reference, first variable must be created, for example:

int var = 5555;

Now pointer to a variable:

int *ptrVar = &var;

And now reference to variable using ampersand symbol between data type and reference name:

int & varRef = var;

Knowing pointers and references, we can get value in a variable:

cout << "Value in var: " << var << endl;
cout << "Value using pointer: " << *ptrVar << endl;

cout << "Value using Reference: " << varRef << endl;

Full script: 

#include <iostream>

using namespace std;

int main() {

    int var = 5555;
    int *ptrVar = &var;

    int & varRef = var;

    cout << "Value in var: " << var << endl;
    cout << "Value using pointer: " << *ptrVar << endl;

    cout << "Value using Reference: " << varRef << endl;

    return 0;

}

Result:

Value in var: 5555
Value using pointer: 5555
Value using Reference: 5555

Process returned 0 (0x0)   execution time : 0.215 s
Press any key to continue.

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...