Changing a const variable?

This is a discussion on Changing a const variable? within the C++ Programming forums, part of the General Programming Boards category; Is it possible to change a const variable without using pointers, subscripts, unions, or casts?...

  1. #1
    Registered User
    Join Date
    Jan 2008
    Posts
    65

    Changing a const variable?

    Is it possible to change a const variable without using pointers, subscripts, unions, or casts?

  2. #2
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,047
    Well . . . you could declare it mutable.

    Or you could print the address to the screen and demand that the user enters the exact address again, and modify that.

    Or you could edit the source code. That's changing the variable, isn't it?

    Or you could be very sneaky and unportable . . . .
    Code:
    int *p, x;
    const int c = 3;
    
    p = &x + 1;
    *p = 4;
    // now c is 4!
    Okay, that was really bad, and it probably wouldn't work anyway. Certainly not reliably.
    Last edited by dwks; 08-31-2008 at 08:43 PM.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  3. #3
    and the hat of sweating
    Join Date
    Aug 2007
    Location
    Toronto, ON
    Posts
    3,545
    I thought mutable only lets const functions change a member variable?

  4. #4

    Join Date
    Apr 2008
    Location
    USA
    Posts
    76
    AFAIK, changing a const variable results in undefined behavior and can only be done with unions, pointer arithmetic, const_cast, or placement new.

    Mutable just means a member of a class/struct will never be const:
    Code:
    struct MyStruct
    {
                int a;   // Const-ness of 'a' depends on instantion
       mutable  int b;   // 'b' is never const (even if instance is const)
       const    int c;   // 'c' is always const (even if instance isn't const)
    };

  5. #5
    Registered User
    Join Date
    Apr 2006
    Posts
    2,050
    Mutable is the only option that doesn't involve pointers or casts.

    Rudyman, you are correct except that in your example b is a part of MyStruct, and therefore a change to b is a change to MyStruct. Thus though the use of mutable the state of a const variable can be changed.
    It is too clear and so it is hard to see.
    A dunce once searched for fire with a lighted lantern.
    Had he known what fire was,
    He could have cooked his rice much sooner.

  6. #6
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,659
    If you really need to change it, perhaps you should rethink the "const".
    Your thread title is a dead giveaway.
    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.

  7. #7
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,768
    There is a const_cast in C++ that defines a defined way of removing const. It should only be used as last retort.
    As Salem says, if you need to modify const, then you should look back at the problem again and think hard, and really see if you really need to change the const.
    Perhaps you should post your little problem so others can see if it's necessary or find a better solution?
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  8. #8
    Registered User
    Join Date
    Jun 2005
    Posts
    6,428
    Quote Originally Posted by jw232 View Post
    Is it possible to change a const variable without using pointers, subscripts, unions, or casts?
    The easiest way is to remove the const keyword and recompile

    Another way, if you're willing to lock yourself into a specific compiler and system (ie sacrifice all portability) is to use the asm keyword to introduce a suitable assembler construct to do what you want.

  9. #9
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,893
    The compiler assumes that a constant doesn't change. If you use any dirty tricks to break that assumption (pointer casts, const casts, assembly), you'll just get miscompiled code and extremely elusive bugs.

    The question betrays a very fundamental misconception about something.
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  10. #10
    Registered User
    Join Date
    Jan 2008
    Posts
    65
    Please, don't assume the reason I ask. This was a challenged posed in a C++ book.

  11. #11
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by jw232 View Post
    Please, don't assume the reason I ask. This was a challenged posed in a C++ book.
    In which case I would say that the answer is probably a simple "no".

    (This is to examplify the problem - I'm not sure the syntax is actually valid!):
    Code:
    // file1.c
    class A
    {
       public:
          const int x = 7; 
       ...
    };
    
    extern void func(A &a);
    
    int main()
    {
       A a;
       func(a);
    }
    
    //file2.c:
    class A
    {
       public:
          int x = 7;   // Not missing const!
       ...
    };
    
    void func(A &a)
    {
       a->x++;
    }
    But we are no[color="Red"w[/color] breaking some of the good coding standards that we should all follow. (And it's using "pointers in disguise" under the name of references).

    Edit: in red above

    --
    Mats
    Last edited by matsp; 09-01-2008 at 09:15 AM.
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  12. #12
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,659
    > This was a challenged posed in a C++ book.
    Which book (noting that there are in fact a lot of crap books on C++, and precious few good ones).
    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.

  13. #13
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,893
    The misconception could be on part of the book. Please give us the name of the book and the context of the question - most likely we'll have to warn people away from it now.

    matsp: That's a violation of the ODR. No diagnostic required, but the program has undefined behaviour, like any other program that attempts to change a const variable.
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  14. #14
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by CornedBee View Post
    The misconception could be on part of the book. Please give us the name of the book and the context of the question - most likely we'll have to warn people away from it now.

    matsp: That's a violation of the ODR. No diagnostic required, but the program has undefined behaviour, like any other program that attempts to change a const variable.
    ODR = "One Declaration Rule"? Yes, I agree that it's essentially using a union in disguise, and it's definitely "bad coding standards" anyways. I'm just trying to find some way that would actually achieve this.

    And yes, I agree that I wouldn't expect the compiler to come up with a x that is different from 7 if we added code to output x after the call to func - as far as the compiler is concerned, it does not expect x to be anything different from 7 - so it can replace all places where x is used with the number 7 as a constant. Job done. The func code would then access 4 bytes that isn't actually x (it may be some other member variable or some random data beyond the size of the variable, for example). That is not what the programmer who wrote such a thing would expect.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  15. #15
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,893
    "One Definition Rule". You may have multiple declarations, but only one definition per translation unit. Furthermore, there may be only one definition of a non-inline, non-template function across all translation units. Finally, if there are multiple definitions of anything else across translation units (e.g. a class definition in a header), they must all be identical on the token level.
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. seg fault at vectornew
    By tytelizgal in forum C Programming
    Replies: 2
    Last Post: 10-25-2008, 01:22 PM
  2. Undefined Reference Compiling Error
    By AlakaAlaki in forum C++ Programming
    Replies: 1
    Last Post: 06-27-2008, 11:45 AM
  3. Another problem with templates
    By robatino in forum C++ Programming
    Replies: 8
    Last Post: 09-21-2006, 04:32 PM
  4. vector<>
    By teval in forum C++ Programming
    Replies: 11
    Last Post: 08-18-2003, 03:27 PM
  5. simulate Grep command in Unix using C
    By laxmi in forum C Programming
    Replies: 6
    Last Post: 05-10-2002, 04:10 PM

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