Casting volatile and const variables

R

ramu

Hi,
I read somewhere in the web that const and volatile variable
shoult not be type casted. Can you please tell me why shouldn't we
type cast const and volatile variables?

Regards
 
B

Ben Bacarisse

ramu said:
I read somewhere in the web that const and volatile variable
shoult not be type casted. Can you please tell me why shouldn't we
type cast const and volatile variables?

[Aside: I don't like using cast as a verb and I particularly dislike
"type cast" as a verb because of its plain English meaning. A cast
operator simple converts a value from one type to another, and it is
the conversion that is important, not the operator that does it. In
other words you can simply talk about "conversions" rather than "casts"
and be using simpler English whilst covering a wider range of cases.
Both unsigned int x = -1; and (unsigned int)-1 perform a conversion
from signed to unsigned int, and it is the conversion that most
people mean when they talk about "casting to unsigned". Of course,
some conversions can only be done with a cast, but I still think the
plain English term is better.]

I think the text you read is misleading you. Maybe it said that you
should not "cast away" the effect of the const or volatile type
qualifiers? That may be sound advice, but only in the trivial sense
that those qualifiers serve a purpose, and removing them will
therefore prevent that purpose being served.

Note that const and volatile only mean anything when applied to
objects. Converting the value of a cont double object to, say, an int
value is harmless and is not what people mean by "casting away" const.
Given:

const double pi = 3.14;
printf("%d\n", (int)pi);

the const removal is harmless. But given:

const char *str = "pi";
strcpy((char *)str, "3");

The cast removes the qualifier const form _the object pointed to_ by
"str", and is a clear sign of something very dangerous (and in this
case plain wrong).
 

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

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,020
Latest member
GenesisGai

Latest Threads

Top