Why does #define INVALID_VALUE -999; give a syntax error when used?

后端 未结 6 2101
长发绾君心
长发绾君心 2020-12-11 22:40

I am trying to compare to a defined constants in C, and I have simplified my program to the following:

#include \"stdio.h\"
#include \"stdlib.h\"
#define INV         


        
6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-11 23:43

    You need to remove the ; in #define INVALID_VALUE -999;. See the fixed code.

    You could have worked towards this conclusion by understanding what the error message expected ‘)’ before ‘;’ token was telling you. It's telling you that it expected to find a ) before the ; token, but from inspecting the line alone you don't see a ;. So maybe there's one in the definition of INVALID_VALUE? Look up at #define INVALID_VALUE -999; and there it is! Think it should be there, but not sure? So let's try remove it and see if it works. Success!

    This page goes and explains why you shouldn't conclude a #define with a semicolon, even if it is needed in the use of the macro. It's good to learn as much as possible from your mistake so that you don't make it again. Quote:

    Macro definitions, regardless of whether they expand to a single or multiple statements should not conclude with a semicolon. If required, the semicolon should be included following the macro expansion. Inadvertently inserting a semicolon at the end of the macro definition can unexpectedly change the control flow of the program.

    Another way to avoid this problem is to prefer inline or static functions over function-like macros.

    In general, the programmer should ensure that there is no semicolon at the end of a macro definition. The responsibility for having a semicolon where needed during the use of such a macro should be delegated to the person invoking the macro.

提交回复
热议问题