+ 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; }

27th Jan 2021, 9:00 PM
Edward Finkelstein
Edward Finkelstein - avatar
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.
27th Jan 2021, 10:48 PM
Mike A
Mike A - avatar
+ 2
Jegix this makes sense, thanks
27th Jan 2021, 11:05 PM
Edward Finkelstein
Edward Finkelstein - avatar
+ 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; }
27th Jan 2021, 10:31 PM
Maher Al Dayekh
Maher Al Dayekh - avatar