const vs. #define

Ed McNierney ed at TOPOZONE.COM
Thu Oct 19 14:39:18 EDT 2006


Ned -

Yes, but to my eyes, your first example is an error and it SHOULD fail
and not "work perfectly", so there is nothing wrong.  Part of the goal
here is to use the right constructs to help catch coding errors, and if
I had written the code in your example I would be making an error and it
would be caught by the compiler.

I think it comes down to a recognition that #define and const are two
different things doing two different jobs, and there is a right time and
a wrong time to use each.

	- Ed 

-----Original Message-----
From: UMN MapServer Developers List [mailto:MAPSERVER-DEV at LISTS.UMN.EDU]
On Behalf Of Ned Harding
Sent: Thursday, October 19, 2006 2:01 PM
To: MAPSERVER-DEV at LISTS.UMN.EDU
Subject: Re: [UMN_MAPSERVER-DEV] const vs. #define

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