Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!usc!srhqla!demott!kdq From: kdq@demott.com (Kevin D. Quitt) Newsgroups: comp.lang.c Subject: Re: When do you use const Keywords: const, #define, C Message-ID: <1991Feb2.181948.2147@demott.com> Date: 2 Feb 91 18:19:48 GMT References: <1220@tredysvr.Tredydev.Unisys.COM> Organization: DeMott Electronics Co., Van Nuys CA Lines: 28 In article <1220@tredysvr.Tredydev.Unisys.COM> paul@tredysvr.Tredydev.Unisys.COM (Paul Siu) writes: >In ANSI C, you can define a variable as constant by preceeding it with const. >You can for example define a double variable x that you cannot change by > > const double x; > >However, what is the advantage of using const over #define? Why was the >reason for its addition to ANSI C. 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. Another advantage is in the optimization phases, where the const keyword provides more information to the optimizer. -- _ Kevin D. Quitt demott!kdq kdq@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