40

What does const really mean? Read-only seems to encapsulate its meaning for me, but, I'm not sure I'm right.

If read-only and const are different, could someone tell me why?

What prompted this question was this answer where he states const "just" means read-only in C. I thought that's all const meant, regardless of whether it was C or C++. What does he mean?

For an answer to the specific differences in const in C vs C++, I've created a new question: How does "const" differ in C and C++? as per R..'s suggestion.

Community
  • 1
  • 1
Kim Sun-wu
  • 1,620
  • 1
  • 18
  • 26

7 Answers7

55

By declaring a variable as const you indicate compiler that you have no intentions of modifying that variable. But it does not mean others don't have! It's just to allow some optimization and to be notified by a compile error (note, that it's mostly compile error, while const == ReadOnly would mean runtime errors).

const does not mean read only, because you can write const volatile, that would mean it could change by itself anytime, but I have no intentions to modify it.

EDIT: here is a classical example: consider I'm writing the code that reads current time from a memory-mapped port. Consider that RTC is mapped to memory DWORD 0x1234.

const volatile DWORD* now = (DWORD*)0x1234;

It's const because it's a read-only port, and it's volatile because each time I will read it it will change.

Also note that many architectures effectively make global variables declared as const read-only because it's UB to modify them. In these cases UB will manifest itself as a runtime-error. In other cases it would be a real UB :)

Here is a good reading: http://publications.gbdirect.co.uk/c_book/chapter8/const_and_volatile.html

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
ruslik
  • 14,714
  • 1
  • 39
  • 40
  • 1
    @ruslik: "by itself"? Could you provide an example? – Kim Sun-wu Dec 20 '10 at 02:05
  • 2
    @Kim: The variable could be mapped to some form of hardware device. Or it could be that Thread A has it const volatile, and it's changed from thread B, or.... any number of things like that. – Billy ONeal Dec 20 '10 at 02:09
  • 1
    A location in memory that is only ever modified by some piece of hardware outside the CPU. Say you have a sensor mapped to a location in memory and you want to read the value it's reporting. – Matt K Dec 20 '10 at 02:10
  • @ruslik, @Billy, @Matt: What would happen in the example ruslik pointed out if the variable was only marked const? The compiler has no idea what's at that location, so it's not going to get optimized away or any such thing, what's the difference between const/const volatile other than making the code more "correct" to the reader? i.e, does it have any implications for the code itself if it was just marked const? const only guarantees that the code itself doesn't modify that location(without an explicit cast), not that any hardware doesn't, right? – Kim Sun-wu Dec 20 '10 at 02:19
  • 4
    According to my english, "read only" means that you can only read it, but not necessarily that it won't change. – Johannes Schaub - litb Dec 20 '10 at 04:29
  • @Kim: If it was only marked const, then the compiler could assume that the value wouldn't change "by itself". So in some circumstances, the compiler *could* optimize away accesses. Initially it doesn't know what's at that location, but once it's been read from, it *does* know, so it doesn't need to do the same read again the *next* time you read from that location. Normally, the compiler can (and will) assume that two reads, with no writes in between, will yield the same result, and optimize accordingly. `volatile` tells the compiler not to make this assumption – jalf Dec 20 '10 at 06:01
  • This is a bit of an over-generalization. There are cases where the compiler can't be sure if you *might* have modified it. Continuing rusliks example, say that you read from `now`, then write to *another* non-const `DWORD*`. Now the compiler has to assume that *maybe* the write you just peformed was to the same address that `now` points to, so maybe `now` has changed. But short of such pointer aliasing, the compiler can assume that unless a variable is marked `volatile`, it'll contain the same value if you read it two times in a row. – jalf Dec 20 '10 at 06:05
  • Jalf is correct: it doesn't necessarily mean that something outside of the *CPU* is doing the modifying; just something outside of the function / module / program, that the compiler wouldn't normally expect. The point is to warn the compiler not to make assumptions; not to optimise based on assumptions, in particular. –  Apr 18 '14 at 23:23
9

The compiler won't allow something declared as const to be modified. It is as you say.

It's mostly used in function prototypes to inform the user that a function won't touch this or that when passed pointers. It also works as kind of failsafe for yourself.

salezica
  • 74,081
  • 25
  • 105
  • 166
  • 4
    +1 For "failsafe for yourself." If you know you shouldn't be changing something, declare it as a `const` and avoid potential errors later on. – Maxpm Dec 20 '10 at 02:03
2

A lot of people are telling you that const means you can't modify it. That is patently false. const can trivially be cast away. Note this snippet:

void foo(const int *somevalue)
{
   int *p = (int*) somevalue;
   *p = 256;  // OMG I AM EVIL!!!!11
}

Your compiler will not stop you from doing this. So, what then is the purpose of const? I'd call it more of a suggestion. It reminds you as you look at function prototypes of the contract that your functions expect. Your compiler will yell at you if you carelessly break it. (But not if you intentionally break it, as with the above cast.)

In some cases the standard intentionally breaks const. Note the return values of strstr for example: by definition it will return some offset into the const buffer you provide it... But the returned value is not const. Why? Well, this would break meaningfully using the return value of strstr on a non-const buffer.

asveikau
  • 39,039
  • 2
  • 53
  • 68
  • 9
    This code has undefined behavior if the object you actually passed a pointer to was declared `const`. The only time it's valid to write through a pointer from which `const` qualification was removed is if the originally pointed-to object was non-`const`. The same applies with other qualifiers like `volatile`. – R.. GitHub STOP HELPING ICE Dec 20 '10 at 02:20
  • 4
    @R.. - I was going to write something like this, actually, but thought it might be distracting to describe... A common example is: If you declare something `const` outright, your compiler may put it in a read-only data section and you could crash writing to it. – asveikau Dec 20 '10 at 02:24
1

Two byte for byte identical (except for the comments) minimal case examples...

First in C, gcc will emit a warning...

/* Function taking a pointer to an array of
 two read only integers.*/
void a( const int (* parray)[2]);

void b(void)
{
   int array[2] = {1,2};
   const int crray[2] = {1,2}; 
/* C reserves the right to stash this in a read-only location.*/
   
   a( &array); 
/* warning: passing argument 1 of ‘a’ from incompatible pointer type*/
   a( &crray); /* OK!*/
}

Now the same thing in C++... g++ is quite happy with it.

// Function taking a pointer to an array 
// of two integers which it promises not to modify. 
// (Unless we cast away it's constness ;-P)
void a( const int (* parray)[2]);

void b(void)
{
   int array[2] = {1,2};
   const int crray[2] = {1,2};
   
   a( &array); // C++ has no problem with this.
   a( &crray); // OK!
}
aSemy
  • 5,485
  • 2
  • 25
  • 51
  • 2
    This example doesn't actually show what you think it is showing, it is just an oversight in the C language specification. [See here](http://stackoverflow.com/questions/28062095/pass-a-two-dimensional-array-to-a-function-of-constant-parameter/28062262#28062262) for related answer – M.M Feb 18 '15 at 01:09
0
const char * hello_1{ "Hello!" };
const char   hello_2[]{ "Hello!" };
char       * ptr{};

// take away the const-nes
// ptr = (char *)hello_1;
// *ptr = '*'; <-- write access violation
// hello_1 is in a read only memory

// take away the const-nes
ptr = (char *)hello_2;
*ptr = '*'; // <-- OK
// hello_2 is modifiable

Pointers point to memory, and char * points to memory in the data segment which is read only. The difference between char * and char [] is that while both are declared the same way on the data segment, char [] is treated as readable because it is pushed onto the stack if it is used.

  • `hello_2` *might* be on the stack, or applying the as-if-rule, it might not. In either case, UB it stays. – Deduplicator Jun 24 '18 at 12:09
  • @Deduplicator, kindly show us the code where hello_2 is not on the stack? –  Jun 25 '18 at 10:03
  • You really should differentiate between "that's what happens on my machine with these options now" and "that's what is guaranteed to happen". The former is cowboy-coding of the worst kind, with all the brittleness it implies, the latter coding to the interface, and the only way to get reliable software. – Deduplicator Jun 25 '18 at 10:49
  • @Deduplicator. ok that is understandable. Can we now please see what did you meant with your comment? We are not experts. –  Jun 25 '18 at 12:06
-2

C++ allows for the definition of const member functions. const member functions are the only functions that be called on const objects. Also, const member functions cannot modify any data members of a class (unless the data member marked mutable).

class Foo
{
    int data;

    void Bar();
    void ConstBar() const;
};

void Foo::ConstBar() const
{
    // Error! cannot modify i as ConstBar is a const member function.
    // i = 0;
}

// Usage:
const Foo foo_instance;

// Error! cannot call non-const member on a const object.
// foo_instance.Bar();

// OK
foo_instance.ConstBar();
Sonny Saluja
  • 7,193
  • 2
  • 25
  • 39
  • Didn't realize you were looking for a very specific answer. The way your question was worded kinda threw me off. – Sonny Saluja Dec 20 '10 at 02:34
  • there is no such thing as a const object, nor a const type (despite the incorrect description in the Standard). Your code is correct though: but it is not the object which is const, but the reference or pointer to that object. BTW: in the example you mean "data" not "i". And note: ((Foo*)this)->data = 1; modifies data even inside ConstBar :) – Yttrill Dec 20 '10 at 09:05
-4

Const means that a pointer or reference cannot be used for a write or read-modify-write operation without casting away const. It does NOT mean what the C++ standard tries to claim it means (the C++ standard is just wrong on this).

A variable defined like this:

 /* auto */ int const x = 1;

is patently NOT read-only since otherwise it could not be initialised. Rather, the kind of variable x is "reference const to int" (and NOT reference to const int) or alternatively lvalue const of int. Note carefully the "const" is associated with a pointer or reference it has nothing to do with the storage, nor the type of the value residing in that storage.

This is rather unfortunate because the contract provided by const is extremely weak, and in particular fails to allow caching of a pointed at or referred to memory location, precisely because it does NOT mean immutable storage.

The bottom line is: const is an access modifier associated with a symbolic reference or pointer which is used by the programmer to allow the symbol provider to establish an obligation on the symbol client, or for the symbol client to promise the symbol provider it does not modify storage via this symbol (for example a function accepting a pointer const to int promises not to modify the pointed at int).

This has nothing to do with variables:

int const *p = (int*)malloc(sizeof(int));

and clearly little to do with storage (malloc'ed store is always writable).

Instead you should think of const as a way of communicating invariants, obligations or requirements between parts of the program, put in place by the programmer for the programmers purposes, and propagated by the type system. Unfortunately the type system isn't sound and fails to properly propagate constness correctly:

X *last;
struct X { int a; X() : a(0) { last=this; } };
X const x; // x is const?
last->a = 1; //really ??

IMHO the only opportunity a compiler has to make store immutable is for actual constants such as string literals (maybe) or static (global) storage. Automatic, heap, and temporary storage cannot be made read-only in practice.

Yttrill
  • 4,725
  • 1
  • 20
  • 29