const reference

E

Esteban Osses

Hi all,

If I have this code:

{
const int& c = 10;
// ...
}

I can read `c' anywhere in this scope, and I can always modify its
value via `const_cast<int&>(c)'

my questions are:

is there anything wrong with that declaration of `c' or using `c' later
in the program? if not, is there anything good on that declaration, any
advantage or something?

Thanks
 
V

Victor Bazarov

Esteban said:
If I have this code:

{
const int& c = 10;
// ...
}

I can read `c' anywhere in this scope,
Sure.

> and I can always modify its
value via `const_cast<int&>(c)'

Not without invoking undefined behaviour you can't.
my questions are:

is there anything wrong with that declaration of `c' or using `c' later
in the program?

I am not sure I understand the question. Aside from the fact that it's
probably not necessary to have a reference and better to have a plain
const value

const int c = 10;

, I don't immediately see anything wrong.
> if not, is there anything good on that declaration, any
advantage or something?

I don't think so.

V
 
K

Karl Heinz Buchegger

Esteban said:
Hi all,

If I have this code:

{
const int& c = 10;
// ...
}

I can read `c' anywhere in this scope, and I can always modify its
value via `const_cast<int&>(c)'

You can, but you shouldn't. The simple rule is: 'Don't lie to your compiler'.
If you declare something as const, don't try to modify it, or you will immediatly
be sent into 'land of undefined behaviour'.
is there anything wrong with that declaration of `c' or using `c' later
in the program? if not, is there anything good on that declaration, any
advantage or something?

You are asking the wrong questions.
The real question must be: "Why do you want to modify something that you
explicitely declared to not change?"
Either it is constant, then you should say so and not try to modify it.
Or it is not constant, then you also should say so and for heavens sake modify
it.

The point is: The compiler will take your word for it and arange everything
the way you defined it. If you later use tricks to work around your own
definitions, it is not the compilers fault, if the compilers arrangement
isn't corect.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,680
Members
48,796
Latest member
Greg L.

Latest Threads

Top