Path: utzoo!attcan!uunet!taumet!steve From: steve@taumet.com (Stephen Clamage) Newsgroups: comp.lang.c++ Subject: Re: #defines.... Message-ID: <303@taumet.com> Date: 4 Jul 90 17:08:49 GMT References: <37786@genrad.UUCP> <5005@castle.ed.ac.uk> Reply-To: steve@taumet.UUCP (Stephen Clamage) Organization: Taumetric Corporation, San Diego Lines: 44 In article <5005@castle.ed.ac.uk> ecsv38@castle.ed.ac.uk (S Manoharan) writes: >[when to use #define in C++] >1. To avoid multiple inclusion of header files. Thus creating a maintenance nightmare when one #define changes and another doesn't. >2. Macros local to a function. As in: >#define _C(i,j) ( *(C + nelements * i + j) ) >where C is ptr, and _C(i, j) defines element [i, j] of an array. >Note that an inline can't be local to a function. But you can still do this with non-local inlines: inline SomeType *_C( SomeType *C, int nelements, int i, int j) { return C + nelements * i + j; } usage: ... + * _C(C, nelements, i, j) + ... * _C(C, nelements, i, j) = 0; This generates exactly the same code as the macro (for any reasonable compiler) and does not have the flaws of macros. Macros have no scope, and sometimes intrude where they are not wanted. Your example would have to start with #undef _C /* in case previously defined */ and end with #undef _C /* so it doesn't cause problems later */ But what if _C were defined as a global macro somewhere? It is now lost. If you don't use macros, they don't cause problems. I am not speaking of toy programs where one programmer holds the entire design in his head, but of real-world multi-programmer projects. A minor quibble: Identifiers beginning with an underscore and an uppercase letter are reserved. But that is irrelevant to this discussion. Second quibble: 2-dimensional arrays possibly could be used to avoid writing this code at all (but not in all applications). -- Steve Clamage, TauMetric Corp, steve@taumet.com