2

Based on corrections of annotations to the standard.

3.14 An object is either a variable or a constant that resides at a physical memory address.

  • In C, a constant does not reside in memory, (except for some string literals) and so is not an object.

It makes sense to me that a const will not have an actual memory location (except possibly for string literals) and that it depends on the compiler, which will most likely replace all references to it with the literal value. That being said, how is the following possible?

const int * foo;

This declares a pointer to a const int. However, constants don't have an address, so what does this really mean? You can't have a pointer to a literal value that only exists at compile time.

Pavan Manjunath
  • 27,404
  • 12
  • 99
  • 125
Anthony
  • 604
  • 6
  • 18
  • 2
    In retrospect, `const` should have been named "readonly". That's what it usually means in C: a readonly object. – pmg May 08 '12 at 17:37
  • 1
    A `const` does not mean a compile-time constant. Instead it is a "type qualifier". This simply means that a `const` cannot be used as the target of an assignment. Here's some interesting discussion: http://stackoverflow.com/questions/4275504/deep-analysis-of-const-qualifier-in-c – Greg Inozemtsev May 08 '12 at 17:43
  • 1
    `const int a = 10;` , `10` is the "constant", the author should really have said "literal". `a` is not the "constant", even though it has the const qualifier. `10` does not have an address (which probably lead the author to say it doesn't reside in memory, though that's irrelevant and largely false). `a` does have an address. – nos May 08 '12 at 17:46

2 Answers2

4

A const variable is not a constant. A constant is a literal value or an expression composed of literal values, like 3+5/2.4. Such constants indeed don't reside in memory, the compiler inserts the literal at the appropriate places.

Daniel Fischer
  • 181,706
  • 17
  • 308
  • 431
3

In your example, foo is not a constant, it is a const-qualified object:

6.7.3 Type qualifiers

Syntax

1     type-qualifier:
        const
        restrict
        volatile

...
3 The properties associated with qualified types are meaningful only for expressions that are lvalues.114)
...
114) The implementation may place a const object that is not volatile in a read-only region of storage. Moreover, the implementation need not allocate storage for such an object if its address is never used.
John Bode
  • 119,563
  • 19
  • 122
  • 198