Preprocessor directive to define a macro
Syntax
#define identifier text
#define identifier([parameters]) macro_text
Description
Preprocessor keyword that defines an identifier with a custom meaning:
- Non-empty defines (with text) are substituted by its text when the source is parsed, allowing a sort of "shorthand". text may be empty, which is useful for making defines that are just designed for checking with #ifdef and #ifndef.
- Defines with parameters are substituted by the macro_text, that will contain all the arguments passed replaced. Note: The open parentheses character ("(") must immediately follow the identifier, there should be no white-spaces between them, otherwise the parentheses will be taken as part of text.
- Defines are visible only in the scope where they are defined. If defined at module level, the define is visible throughout the module. If the identifier is defined inside a compound statement having scope (Sub, For..Next, While..Wend, Do..Loop, Scope..End Scope, etc), the identifier is visible only within that scope.
- Namespaces do not have any effect on the visibility of a define.
Identifiers can be checked to see whether they have been defined with
#ifdef and
#ifndef, which can be used to hide parts of code to the compiler (conditional compiling).
For defining identifiers with constant values associated with them
Const may be used as a more powerful method.
Example
'' Definition and check
#define DEBUGGING
#ifdef DEBUGGING
' ... statements
#endif
'' Simple definition/text replacement
#define FALSE 0
#define TRUE (Not FALSE)
'' Function like definition
#define MyRGB(R,G,B) (((R)Shl 16) Or ((G)Shl 8) Or (B))
Print Hex( MyRGB(&hff, &h00, &hff) )
'' Line continuation and statements in a definition
#define printval(bar) _
Print #bar; " ="; bar
'' #defines are visible only in the scope where they are defined
Scope
#define LOCALDEF 1
End Scope
#ifndef LOCALDEF
# Print LOCALDEF Is Not defined
#endif
'' namespaces have no effect on the visibility of a define
Namespace foo
# define NSDEF
End Namespace
#ifdef NSDEF
# Print NSDEF Is defined
#endif
Differences from QB
See also