Preprocessor directive to define a macro
Syntax
#define identifier text
#define identifier( [ parameters ] ) macro_text
#define identifier( [ parameters, ] variadic_parameter... ) 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.
Using
... (an ellipsis) behind the last parameter of a macro allows to create a variadic macro. This means it is possible to pass any number of arguments to the
variadic_parameter, which can be used in the
macro_text, just like a normal macro parameter. The
variadic_parameter will expand to the full list of arguments passed to it, including commas, and can also be completely empty.
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
'' Using a variadic macro to wrap a variadic function
#include "crt.bi"
#define eprintf(Format, args...) fprintf(stderr, Format, args)
eprintf(!"Hello from printf: %i %s %i\n", 5, "test", 123)
'' LISP-like accessors allowing to modify comma-separated lists
#define car(a, b...) a
#define cdr(a, b...) b
Differences from QB
See also