Constant Pointers and Constant Data

Posted on 2006-04-25
Last Modified: 2008-03-10
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?
Question by:UrosVidojevic
    LVL 23

    Expert Comment

    Statement No. 5 performs an explicit cast (int *) that overrides the defined type of kpkb.
    LVL 27

    Accepted Solution

    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:

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

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    Threat Intelligence Starter Resources

    Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

    Preface I don't like visual development tools that are supposed to write a program for me. Even if it is Xcode and I can use Interface Builder. Yes, it is a perfect tool and has helped me a lot, mainly, in the beginning, when my programs were small…
    Summary: This tutorial covers some basics of pointer, pointer arithmetic and function pointer. What is a pointer: A pointer is a variable which holds an address. This address might be address of another variable/address of devices/address of fu…
    The goal of this video is to provide viewers with basic examples to understand opening and writing to files in the C programming language.
    The goal of this video is to provide viewers with basic examples to understand how to use strings and some functions related to them in the C programming language.

    737 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    21 Experts available now in Live!

    Get 1:1 Help Now