I was writing some test code in C. By mistake I had inserted a ;
after a #define
, which gave me errors. Why is a semicolon not req
The second version does not define a constant as far as the language is concerned, just a substitution rule for a block of text. Once the preprocessor has done it's job, the compiler sees
char buffer [256;];
which is not syntactically valid.
The moral of the story: prefer the const int MAX_STRING = 256;
way as that helps you, the compiler, and the debugger.
define
is a preprocessor directive, and is a simple replacement, it is not a declaration.
BTW, as a replacement it may contain some ;
as part of it:
// Ugly as hell, but valid
#define END_STATEMENT ;
int a = 1 END_STATEMENT // preprocessed to -> int a = 1;
#define
is a preprocessor directive, not a statement or declaration as defined by the C grammar (both of those are required to end with a semicolon). The rules for the syntax of each one are different.
Because that is how the syntax was decided for the precompiler directives.
Only statements end with a ;
in c/c++, #define
is a pre-processor directive and not a statement.
Both constants? No.
The first method does not produce a constant in C language. Const-qualified variables do not qualify as constants in C. Your first method works only because past-C99 C compilers support variable-length arrays (VLA). Your buffer
is a VLA in the first case specifically because MAX_STRING
is not a constant. Try declaring the same array in file scope and you'll get an error, since VLAs are not allowed in file scope.
The second method can be used to assign names to constant values in C, but you have to do it properly. The ;
in macro definition should not be there. Macros work through textual substitution and you don't want to substitute that extra ;
into your array declaration. The proper way to define that macro would be
#define MAX_STRING 256
In C language, when it comes to defining proper named constants, you are basically limited to macros and enums. Don't try to use const
"constants", unless you really know that it will work for your purposes.
This preprocessor directive:
#define MAX_STRING 256;
tells the preprocessor to replace all MAX_STRING
s with 256;
- and with the semicolon. Preprocessor statements don't need a semicolon at the end. If you put one, the preprocessor actually thinks you mean it with a semicolon.
If you are confused with #define
s for constants, const int
would probably be easier to comprehend.
If you want to learn more on how to properly use these preprocessor directives, try looking at this website.