C++ I/O, Variables and References
#include <iostream>
#include <string>
using namespace std;
int main() {
string name;
int age;
cout << "Enter name and age: ";
cin >> name >> age;
cout << "Hello " << name << ", you are " << age << endl;
auto pi = 3.14159; // type deduced as double
bool ok = true;
cout << boolalpha << ok << " " << pi << endl;
return 0;
}
Enter name and age: Asha 20
Hello Asha, you are 20
true 3.14159
References
A reference is an alias for an existing variable. It must be initialised and can't be re-seated.
#include <iostream>
using namespace std;
void doubleIt(int &n) { n *= 2; } // pass by reference
int main() {
int x = 10;
int &r = x;
r = 25;
doubleIt(x);
cout << x << endl;
return 0;
}
50
Pointer vs ReferenceA pointer can be null and can be re-pointed; a reference can't be null and always refers to the same object.
Track your progress through the C++ course