When do you use const
The Grey Wolf
greywolf at unisoft.UUCP
Wed Feb 6 09:52:49 AEST 1991
In article <1991Feb2.181948.2147 at demott.com> kdq at demott.com (Kevin D. Quitt) writes:
[ const double x; example deleted ]
> Your variable x above is pretty useless, since it has no initialized
>value (and is therefore zero). How about:
>
>const char *foo = "some really long string";
>
> If this is #defined, and is accessed in several places, your
>compiler may save multiple copies of the string. Even if your compiler
>is smart enough to make it a single instance, it won't do this over
>several modules.
I know, I know, not ALL Unices are BSD, and not everyone can do this (yet),
but there is something called xstr on most sensible systems which solves the
#define problem quite nicely across multiple modules.
for module in modules
do cc -E $module.c | xstr -
cc -c x.c
mv x.o module.o
mv x.c module.cx # (if you want to see what it's doing)
done
cc -c xs.c
mv xs.o strings.o
>
> Another advantage is in the optimization phases, where the const keyword
>provides more information to the optimizer.
This does not get solved by xstr :-)...
Where possible, the old method was to use cc -R on the resulting strings
object (xs.o) to make the strings shared/read-only[*]. The C shell is
compiled like this. What with the advent of ANSI C, it appears that the
need for such a compiler flag has been obsoleted by the presence of the
"const" qualifier.
xstr still has its uses -- in places where quoted phrases might be used more
than once (such as {fprintf(stderr,"ioctl: "); perror(arg);} sequences)
all references to the quoted phrase would get changed to be pointers to
the master string array.
>
>
>--
> _
>Kevin D. Quitt demott!kdq kdq at demott.com
>DeMott Electronics Co. 14707 Keswick St. Van Nuys, CA 91405-1266
>VOICE (818) 988-4975 FAX (818) 997-1190 MODEM (818) 997-4496 PEP last
--
thought: I ain't so damb dumn! | Your brand new kernel just dump core on you
war: Invalid argument | And fsck can't find root inode 2
| Don't worry -- be happy...
...!{ucbvax,acad,uunet,amdahl,pyramid}!unisoft!greywolf
More information about the Comp.lang.c
mailing list