Why does #define not require a semicolon?

前端 未结 7 1006
无人及你
无人及你 2020-11-27 21:03

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

7条回答
  •  臣服心动
    2020-11-27 21:43

    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.

提交回复
热议问题