• C

Constant Pointers and Constant Data

Hi, I have this useless program.

main() {
 int a=2, *pa=&a, *const kpa=&a;
 const int b=5, *pkb=&b, *const kpkb=&b;

 pkb=pa;              // 1.) OK
 *pkb=4;              // 2.) ERROR, because value that is pointed by pkb is constant.
 kpa=pa;              // 3.) ERROR, because kpa is a constant pointer.
 pa=kpkb;            // 4.) ERROR, because with pa we could change constant value that is pointed by kpkb.

 pa = (int*)kpkb;   // 5.) Correct! <---------- Why?

 *pa=4;               // 6.) OK.
}


And I understand why statemants 1, 2, 3, 4 and 6 are correct (incorrect), but I don't understand why statemant No. 5. is correct. What makes it different from statemant No 4? Can someone help me?
LVL 7
UrosVidojevicAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

brettmjohnsonCommented:
Statement No. 5 performs an explicit cast (int *) that overrides the defined type of kpkb.
Artysystem administratorCommented:
The difference is an explicit type cast:
in 5) you cast from (int * const) to (int *), it's correct. Then you assigns (int *) to (int *), thats also correct.
in 4) you dont cast and tries to assign (int * const) to (int *) it's an error (you have different types on the left and on the right) and no implicit cast possible.

Read here: http://www.possibility.com/Cpp/const.html

'C++ does not supply a standard conversion from a const type to a type that is not const.'

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C

From novice to tech pro — start learning today.