The #define preprocessor directive is severely overused in my opinion.
Often, you will see programmers write something like this:
# define MAX(a, b) (((a) > (b))? (a) : (b))
However doing so is rather dangerous, because the preprocessor replaces things textually.
This means that if you pass in a call to a function, it may happen twice, for example:
MAX(++i, j) will be expanded to
(((++i) > (j))? (++i) : (j))
which is bad.
A much safer (and more common) example is that people will use #define to create a constant variable:
#define MYCONST 10
This too can cause problems if another file depends on the constant and certain other conditions are met.
A safer alternative is to declare a const variable.
The one advantage of using #define for literal constants is that the number will not be stored in memory attached to an object like a const variable will.
Chat with our AI personalities
I'm not exactly sure that this is a question, but here you are:#define YES 1
Conditional inclusion is a trick that some languages must use to prevent multiple declarations of the same symbols. A prime example would be "C++", that typically breaks the interface and implementation definitions into .h and .cpp files, respectively. Since it is common that the .h file will be included in numerous .cpp files that define symbols needed by the implementation, a common method is to use the #define preprocessor directive. For your file "MyClass.h":#ifndef __MyClass_H__#define __MyClass_H__... class definition goes here ...#endif
# define and # undef are compiler directives in C and C++. The # define directive creates a definition for something that will be replaced multiple times in the code. For example: # define HELLO 5 Creates an association between HELLO and replaces it with 5 in the code (for the compiler only). The # undef (undefine) counterpart removes the definition from what the compiler sees. It is usually specified when either the definition should no longer be used or when the definition needs to change.
Actually, the preprocessor is not part of the C compiler, but here you are: #define is meant to define symbols. Examples #define NULL ((void *)0) #define getchar() getc(stdin)
Assembler.