const vs. #define

Ned Harding nharding at EXTENDTHEREACH.COM
Thu Oct 19 14:01:17 EDT 2006


The big problem with #define is that it doesn't respect the correct
scoping rules.

#define ABC 3

...

void temp()
{
	int ABC = 5;
}


That code will fail because ABC is a preprocessor macro and int 3 = 5;
doesn't make sense.  If you had defined it with a const, it all would
work perfectly.  There are other variations of this that are much more
subtle that can can change the meaning of your code without even a
warning.  This is a can be huge problem when you are a consumer of 3rd
party libraries and some #define steps on one of your variables.  A good
example of this is problem windows.h which has a 

#define max ...

Which steps on the std::max() and can sometimes result in a compiler
error not happening when it should have.

Ned.

-----Original Message-----
From: UMN MapServer Developers List [mailto:MAPSERVER-DEV at LISTS.UMN.EDU]
On Behalf Of Ed McNierney
Sent: Thursday, October 19, 2006 11:31 AM
To: MAPSERVER-DEV at LISTS.UMN.EDU
Subject: Re: [UMN_MAPSERVER-DEV] const vs. #define

Mateusz -

Could you give an example of an error that would be detected using const
that would not be detected using #define?  I agree with your premise in
theory, but I'm not sure how that theory applies here.

	- Ed

-----Original Message-----
From: Mateusz Loskot [mailto:mateusz at loskot.net]
Sent: Thursday, October 19, 2006 12:27 PM
To: Ed McNierney
Cc: MAPSERVER-DEV at LISTS.UMN.EDU
Subject: Re: [UMN_MAPSERVER-DEV] const vs. #define

Ed McNierney wrote:
> I can't imagine it makes any detectable difference in the generated 
> code.

If C compiler supports C99 and const qualifier is well supported, using
const than #define should be preferable.
const is language implementation feature, but #define is a preprocessor
feature.
const as a langauge feature, is "detectable" by compiler, so it's faster
to find bugs when misused.
I think it's always worth to use compiler for bugs detection wherever
it's possible.

Cheers
--
Mateusz Loskot
http://mateusz.loskot.net



More information about the mapserver-dev mailing list