L-32 MCS 260 Fri 2 Nov 2001
In this lecture we explained the difference between defining
a constant with a preprocessor directive and using the const.
The program below is an illustration of using const in combination
with pointers.
/* L-32 MCS 260 Fri 2 Nov 2001 : pointers to const must be const
When we compile the program below on a Sun workstation with gcc,
we get the following warning :
constptr.c: In function `main':
constptr.c:5: warning: initialization discards `const' from pointer target type
If we ignore the warning and execute the program, then we see that
the variable five, declared as a constant integer, has taken the value 6.
To prevent such a mishap, the user must declare also the pointer,
pointing to a const, as const. Unfortunately, also with this correction,
the *p = 6 only caused a warning, and not an error... */
#include<stdio.h>
int main ( void )
{
const int five = 5;
int *p = &five; /* wrong */
/* const int *p = &five; */ /* correct */
printf("%d\n", five);
*p = 6; /* should be prohibited ... */
printf("%d\n", five);
return 0;
}
For the remainder of the lecture we reviewed the answer to quiz 10
for the Thursday lab session.