Mark McIntyre said:
[const] just isn't the same keyword as in C++, which probably
confuses some people.
It isn't? `const' has largely the same meaning in C and in C++
as far as I know. There are some differences in which
conversions that change const-ness are allowed implicitly.
There are two other semantic differences I would consider
significant enough to mention:
- C++'s "const" declares actual constants by default, and
- the default linkage of C++ "const" identifiers is different.
(These two are related, unsurprisingly -- "extern const" in C++
means what "const" does in C if the variable is not initialized.
If the variable *is* initialized, though, the C++ "const" is
still a constant.)
In particular, the following is invalid in C:
const int N = 10;
int a[N];
int main(void) {
/* ... code using the array "a" ... */
return 0;
}
but valid in C++ (because N is not a constant in C, but is in C++):
% cc -o t t.c
t.c:2: variable-size type declared outside of any function
% g++ -o t++ -x c++ t.c
% ./t++
% echo $status [examines the value returned from main()]
0
%
Contrariwise, the following works as C but not as C++:
/* file1.c */
const int N = 10; /* note lack of "extern" */
int f2(void);
int main(void) {
return f2();
}
/* file2.c -- a separate translation unit */
#include <stdio.h>
#include <stdlib.h>
extern const int N;
int f2(void) {
int i, *p, ret;
printf("N is %d (we assume it is at least 1)\n", N);
p = (int *)malloc(N * sizeof *p); /* cast required for C++ */
p[0] = 42;
for (i = 1; i < N; i++)
p
= p[0] * (5 - i);
ret = !p[N - 1];
free(p);
return ret;
}
Here, in C, N is shared across the two translation units, but in
C++ file2.c's extern "N" is missing:
% cc -o c file[12].c
% ./c
N is 10 (we assume it is at least 1)
% echo $status
0
% g++ -o c++ -x c++ file[12].c
/tmp/ccg7oeo1.o: In function `f2(void)':
/tmp/ccg7oeo1.o(.text+0xc): undefined reference to `N'
/tmp/ccg7oeo1.o(.text+0x22): undefined reference to `N'
/tmp/ccg7oeo1.o(.text+0x55): undefined reference to `N'
/tmp/ccg7oeo1.o(.text+0x88): undefined reference to `N'
%