I am supposed to determine whether this function is syntactically correct:
int f3(int i, int j) { const int& k=i; ++i; return k; }
I have tested it out and it compiles with my main function.
I do not understand why this is so.
Surely by calling the function f3
I create copies of the variables i
and j
in a new memory space and setting const int& k=i
I am setting the memory space of the newly created k
to the exact the same space of the memory space of the copied i
, therefore any change, i.e. the increment ++i
will result in ++k
which is not possible given that it was set const
Any help is greatly appreciated
int const* is pointer to constant integer This means that the variable being declared is a pointer, pointing to a constant integer. Effectively, this implies that the pointer is pointing to a value that shouldn't be changed.
The int is basically the type of integer type data. And const is used to make something constant. If there is int& constant, then it indicates that this will hold the reference of some int type data. This reference value is constant itself.
You use "const int" if you want to reference a value by name - you use it just like any ordinary int, but you cannot change the value. This does not use any RAM. The value is used as the actual value wherever it is referenced, just like #define.
int const *ptr; We can change the pointer to point to any other integer variable, but cannot change the value of the object (entity) pointed using pointer ptr. The pointer is stored in the read-write area (stack in the present case). The object pointed may be in the read-only or read-write area.
the increment
++i
will result in++k
which is not possible given that it was setconst
That's a misunderstanding.
You may not change the value of the object through k
but it can still be changed through other means. In other words, ++k
is not allowed but ++i
is still allowed, which will indirectly modify the value of k
.
Here's an analogy from a non-computer world.
You may look through the window of a store and see what's inside but you won't be able to change what's inside the store. However, an employee, who is inside the store, can change the contents of the store. You will see that change from
outside. You have const
access or view access to the store while the employee has non-const
access or change access to the store.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With