const comparison in C and C++

Bjarne Stroustrup bs at alice.UUCP
Fri Sep 16 01:43:04 AEST 1988


Doug Schmidt of University of California, Irvine - Dept of ICS writes:

 > Hi,
 > 
 >    Would someone please explain to me the rationale behind C++'s
 > allowance of ``const's'' objects for use with specifying array size
 > declarations, as opposed to ANSI-C's reject of this construct?  For
 > example, the following is legal C++:
 > 
 > ----------------------------------------
 > 
 > const int Bar = 100;
 > int Foo[Bar]; // declares an array of 100 ints
 > 
 > ----------------------------------------
 > 
 > However, this does not work with the ANSI-Cesque compilers I've 
 > tried (gcc, for example).  I'm interested to know the conceptual
 > differences between the two languages on this point.
 > 
 > thank you,
 > 
 >    Doug Schmidt

``const'' was introduced into C++ for three reasons:

	(1) to provide better documentation of interfaces
		(In particular, consts as argument types showing that
		the value of objects would not change within a function)
	(2) to enable the greater use of symbolic constants
		(In particular, integer consts that do not need to be
		allocated as objects unless the programmer explicitly
		requires it by declaring a const `extern' or taking its
		address) This ties in with a desire to reduce the use
		of macros significantly. Note that C++ also introduced
		inline functions.
	(3) to enable use of read only memory for large constant structures
		such as the tables produced by YACC.

The first two reasons was by far the most important to me at the time.
I can only conjecture about the reasons of the ANSI committe, but my reading
of the rumors and the various versions of the definition of `const' in the
ANSI drafts is that originally they latched on to the third reason exclusively
and that over the years the ANSI C definition of const moved slowly towards
the original conception.

Both the ANSI C and the C++ versions of `const' falls a bit short of the ideal
(as is common for programming language features), but the C++ version retains
the concept that unless stated otherwise a const is a relatively local entity
that might be `optimized away' and a valid alternative to a #define or and
enumerator in a header file.

In ANSI C a `const' default has external linkage so you have to allocate
storage for it (just in case) and a `const' may not be used in a constant
expression.



More information about the Comp.lang.c mailing list