Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is `const int& k = i; ++i; ` possible? [duplicate]

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 iand 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 ++iwill result in ++k which is not possible given that it was set const

Any help is greatly appreciated

like image 777
user9078057 Avatar asked Mar 26 '19 22:03

user9078057


People also ask

Why do we use const int?

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.

What is difference between int and const int?

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.

What does const int mean in code?

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.

What is the use of const int in C?

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.


1 Answers

the increment ++i will result in ++k which is not possible given that it was set const

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.

like image 81
R Sahu Avatar answered Sep 30 '22 00:09

R Sahu