[Someone asked about the difference between const and #define -- whether they “used up” memory, and which was “safer”. This was my reply.]

It's true that #define doesn't “use any memory”. But beyond that, both const and #define both have their safe and unsafe aspects.

As you noted, const “takes up memory and has a benefit of type checking.”

There are several other differences:

#define operates purely at compile time. Actually, since it's a preprocessor directive, you can think of it as operating before the main part of the compiler actually starts compiling your code. When you write

	#define NUM1 45
	int array[NUM1];

by the time the main part of the compiler actually starts compiling your code, what it sees is just

	int array[45];
This example also illustrates one of the mildly “unsafe” aspects of #define. if you accidentally write

	#define NUM1 45;
	int array[NUM1];

what the compiler actually sees is then

	int array[45;];
which is a syntax error.

When you write

	const int num2 = 45;
on the other hand, the main part of the compiler allocates a variable, of type int, and initializes it with the value 45, and makes a note to itself that it should complain if you ever try to modify this variable anywhere else in the source file.

The variable num2 will, yes, exist in memory. This means that you can create a pointer pointing at num2, and sometimes, this is important.

Normally we don't worry about the fact that const variables “eat up” memory while #defines do not. Typically we're only talking about a few or a few dozen variables, which aren't going to consume vast amounts of memory in any case.

The only critical disadvantage of const variables in C is that you cannot use them in cases where you need a true compile-time constant. You cannot say

	int array2[num2];
or

	switch(var)
		{
		case num2:

You cannot declare a static or global variable and initialize it with the value of num2.

To summarize, then, we have:

#define:

const:

There might be one or two other differences that I'm forgetting.

It's also worth noting that const behaves differently in C versus C++. In C++, const variables can be used in compile-time constant expressions, and (as I understand it) they don't occupy space at run time if they don't need to.