4 ms·
int x = 5; f(x); // WHAT IS THE VALUE OF X HERE? if you really want to make sure that x is not changed by f, declare it const. Sure, f can cast the constne
by gpderetta 9y ago
int x = 5;
f(x);
// WHAT IS THE VALUE OF X HERE?
if you really want to make sure that x is not changed by f, declare it const. Sure, f can cast the constness away, but then again it could also walk up the stack in C and trash your stack frame anyway. It is UB in either case.
The typesystem in C++ can help protect against Murphy, but (unfortunately) not Machiavelli.
- fredmorcos 9y agoAgreed. But my example isn't about security or UB. It is about the language allowing you to write two IDENTICAL snippets of code that end up meaning two different things without any overloading involved. Like saying something and meaning something else.
- gpderetta 9y agoint x[] = {5}; f(x); // WHAT IS THE VALUE OF X HERE? see, it works in C as well.
- cesarb 9y agoIn C, the value of x in that fragment is still the same: a pointer (ok, not exactly, but something which behaves like a pointer) to a memory location where an int can be stored. The f(x) call can't change that pointer.
- int_19h 9y agoTry doing something like &x, and you'll see that it doesn't actually reliably behave like a pointer.
- fredmorcos 9y agoSo you get my point. 'x' is not going to be modified behind your back and it's pretty clear on the calling site. In C++ it isn't clear.
- gpderetta 9y agoIt is exactly the same between the two cases: the x object (either the array memory location or the integer memory location) can be changed by 'f' because mentioning the 'x' object name in a function call may implicitly converts to the address of the object, i.e. it passes by reference).
- fredmorcos 9y ago> can be changed by 'f' because mentioning the 'x' object name in a function call may implicitly converts to the address of the object (1) They are two different types and (2) it's clear to you at the calling site!