An interesting question about CONST

This is a discussion on An interesting question about CONST within the C++ Programming forums, part of the General Programming Boards category; Code: const int i=125; int *j = const_cast<int *> (&i); (*j) = 256; printf("%d %d\n", i, *j); Why the result ...

  1. #1
    Registered User
    Join Date
    Apr 2007
    Posts
    284

    Question An interesting question about CONST

    Code:
    const int i=125;
    int *j = const_cast<int *> (&i);
    (*j) = 256;
    printf("%d %d\n", i, *j);
    Why the result is "125 256" ?

  2. #2
    The larch
    Join Date
    May 2006
    Posts
    3,573
    Yes, I think the standard says that this is undefined.

    The standard is highly technical though. Google for "C++ standard draft" and see what it has to say about const_cast and cv_qualifiers.

    In any case, const_cast was probably not meant for you to modify variables that you have declared const (they may be put into some read-only memory, and therefore the second pointer, if you try to change the value through it, needs to point to some other write-able memory).

    A valid use is working around old 3rd-party libraries that haven't been written in a const-correct way. There may be situations where you need to cast away const-ness, but not to change the value, but to be able to use this old code.

    Here's a hypothetical example.
    Code:
    #include <iostream>
    
    
    /*suppose this is from a third-part library, 
        that you have paid for and can't change.
        Note, that the first argument is non-const,
        although the function clearly won't change it.
        
        Function returns pointer to 0-terminator if
        character not found.
    */
    char* Find(char* p, char ch)
    {
        for ( ; *p; p++)
            if (*p == ch)
                break;
        return p;
    }
    
    
    /*suppose we wnat to write a better find function,
        that can start search at a chosen position in the string.
        Now we don't want to rewrite everything, but use the
        existing library as much as possible.
        But we certainly want to write const-correct code.
        The function doesn't change the string, hence it is
        declared constant.
    */
    char* better_find(const char* p, char ch, unsigned from)
    {
        /*Problem:
            can't call Find without const_cast, because p is
            constant, and can only be passed to functions that
            guarantee not to change it (const argument).
            It's OK though, because we know for sure, that Find
            will not try to modify it.
        */
        return Find(const_cast<char*>(p) + from, ch);
    }
    
    int main()
    {
        char s[] = "Don't cast away constness unless you need to.";
        std::cout << s << '\n';
        std::cout << Find(s, 'c') << '\n';
        std::cout << better_find(s, 'c', 10);
        std::cin.get();
    }
    Last edited by anon; 04-06-2007 at 10:50 AM.

  3. #3
    Registered User Noir's Avatar
    Join Date
    Mar 2007
    Posts
    218
    Why the result is "125 256" ?
    Why not? const doesn't say you can't change something, it just says you promise not to. You broke your promise, so anything goes.

  4. #4
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,451
    > Why the result is "125 256" ?
    Because your code is broken.

    On seeing the code, the compiler generated
    printf("&#37;d %d\n", 125, *j);
    on the basis that i is a const, and it knows full well what the value is, so it just substituted it inline without having to go looking in a storage location.

    If you want to smash the type system apart with ill advised casting, then that is what you get.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  5. #5
    Deo
    Deo is offline
    Registered User
    Join Date
    May 2005
    Posts
    73
    that is quite interesting.... the last guy was right although without his answer I woulda shrugged my shoulders as well for a good 30 mins... pesky compilers optimizing all over the place.

    Code:
    volatile const int i=125;
    int *j = const_cast<int *> (&i);
    (*j) = 256;
    
    printf("&#37;d %d\n", i, *j);
    This will cause the compiler to behave the way you perhaps were expecting.

    ie:

    Code:
    output: 256 256
    Last edited by Deo; 04-06-2007 at 07:02 PM.

  6. #6
    l2u
    l2u is offline
    Registered User
    Join Date
    May 2006
    Posts
    630
    Why bother with using const?

  7. #7
    Registered User Noir's Avatar
    Join Date
    Mar 2007
    Posts
    218
    Because it helps protect you from making mistakes. Your compiler is really quick and really smart with C++ so you should take advantage of that and use it as a tool to make programming easier.

  8. #8
    The larch
    Join Date
    May 2006
    Posts
    3,573
    I guess l2u meant, why bother with const, if you end up with volatile const.

  9. #9
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,451
    volatile const does have its uses.
    This isn't one of them.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. question about const pointers and const ints
    By WarDoGG in forum C Programming
    Replies: 9
    Last Post: 01-08-2011, 01:11 PM
  2. matrix class
    By shuo in forum C++ Programming
    Replies: 2
    Last Post: 07-13-2007, 01:03 AM
  3. Need help implementing a class
    By jk1998 in forum C++ Programming
    Replies: 8
    Last Post: 04-05-2007, 03:13 PM
  4. Calculator + LinkedList
    By maro009 in forum C++ Programming
    Replies: 20
    Last Post: 05-17-2005, 12:56 PM
  5. "error: incomplete type is not allowed"
    By Fahrenheit in forum C++ Programming
    Replies: 9
    Last Post: 05-10-2005, 09:52 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21