Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

#define and const 2

Status
Not open for further replies.

inetd

Technical User
Jan 23, 2002
115
HK
What is the different between #define and const declaration?

i.e.
#define number 123
#define MyString "Hello"

and,
const int number=123;
const char MyString[]="Hello";

Thanks.
 
A #define is typeless. You could write

#define number 123

char c = number;
short s = number;
long l = number;
long long ll = number;
float f = number;
double d = number;
unsigned int ui = number;
and many others

The compiler won't complain. However, if you declared

const int number = 123;

The compiler would moan about

char c = number;
short s= number;
unsigned int ui = number;

Having said that, if, during a debug session, you wish to change 123 to 321, a change in value of number would hold througout the debug session but you couldn't do this with a #define. However, using #define like this does not demostrate the full power of macros in C/C++.

Depending on what you are doing, a const normally specifies ROM storage. A #define always specifies compile time processing. You can do lots of tricks with #define.

eg
In headerd.h

DECL(red),
DECL(blue),
DECL(green)

In header.h
#define DECL(x) x
enum Colour
{
#include "headerd.h"
};
#undef DECL

In header.cpp
#define DECL(x) #x
const char* ColourStr =
{
#include "headerd.h"
};
#undef DECL

This will declare enums in the header file and their corresponding strings in the source file without having to worry about the order. Maintenance is as simple as just adding another declaration to headerd.h.

 
With a few Words:

Assignments with #define are handled by the Preprocessor.
Assignments with const are handled by the Compiler.

hnd
hasso55@yahoo.com

 
Or in yet other words:
#define Value_X 123
will substitute the text 'Value_X' with '123' througout the text and THEN compile it.
const int Value_X = 123; allocates a memory location and saves the value 123 in it. Totte
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top