#include <iostream>
using namespace std;
int main(){
int a;
return 0;
}
In this code, we initialized a
- however didn’t assign anything to a
. When we declare a variable, we assign a memory space however we never assign a value - its point to a random memory.
#include <iostream>
using namespace std;
int main(){
int a = 0;
cout << a << endl;
cout << &a << endl;
a = 2;
cout<< &a << endl;
return 0;
}
(Example) Output:
0
0x16f976a68
0x16f976a68
Note that we uses &
in here to see it’s memory address. And once we define the value it’s always pointing to the same position inside the pointer
Another example:
#include <iostream>
using namespace std;
int main(){
int a = 0;
int b = 0;
int c = 0;
int d = 0;
cout << "Address of a: " << &a << endl;
cout << "Address of b: " << &b << endl;
cout << "Address of c: " << &c << endl;
cout << "Address of d: " << &d << endl;
return 0;
}
Address of a: 0x16afa2a68
Address of b: 0x16afa2a64
Address of c: 0x16afa2a60
Address of d: 0x16afa2a5c
Note that in here all of the memory are 4 bytes away, which implies that int
’s length is 4 bytes long.
And note in this program
#include <iostream>
using namespace std;
void modify(int &ref) {
ref = 30;
cout << &ref << endl;
}
int main(){
int a = 10;
cout << &a << endl;
modify(a);
cout << a << endl;
return 0;
}
The output
0x16b226a68
0x16b226a68
30
Which we can see that inside the modify, the memory are the same
&
#include <iostream>
using namespace std;
int main(){
int a = 10;
int b = 20;
int &ref = a;
return 0;
}
Value of ref: 10
Address of a: 0x16f412a68
Address of ref: 0x16f412a68
Both of the ref and a using the same address.
To declare a variable of type char : char letter;
Character constants are enclosed in single quotes: char letter = 'x';
string is a class, different from the primitive data types.