+ 2
C++ code
Hello, Can someone explain this C++ code, please? #include <iostream> using namespace std; int main() { int c = 5; const int *a = &c; const int *b = a; cout << *b << endl; cout << *a << endl; a++; cout << *b << endl; cout << *a << endl; return 0; }
3 Réponses
+ 5
Maher Al Dakeyh
That's a good guess (and not that far off) but the 'pointed to' value is marked const - so modifying the value from that pointer would result in a compilation error.
(*a)++; would increment the value of 'c' and would be caught by the compiler.
What is incremented here is the pointer itself. Pointer 'a' initially points to integer 'c'. When it is incremented, it points to the next element (which is the address 1 * sizeof(int) steps ahead) in memory. The value printed doesn't belong to the program so the result is undefined.
+ 2
Jegix this makes sense, thanks
+ 1
Idk if this is 100% true tho
#include <iostream>
using namespace std;
int main() {
int c = 5;
const int *a = &c;// a = 5
const int *b = a; // b = 5(pointer pointing to a variable by another one)
cout << *b << endl;
cout << *a << endl;
a++;
cout << *b << endl;//still b = since a++ increments to itself first, and its equal to a constant value
cout << *a; // garbage value, since a is const
return 0;
}