Colon after #define in Objective-C [duplicate]

2019-09-21 16:34发布

问题:

This question already has an answer here:

  • Why does #define not require a semicolon? 7 answers

In Objective-C you can define macros using the #define

#define kSomeMacro 1024

and then use that macro for something like this...

if (kSomeMacro == 1024) {
   ....
}

However if you define your macro with a colon on the end

#define kSomeMacro 1024;

Then the if statement won't work. What is the reasoning behind this and why doesn't the complier complain if you put a ; when defining the macro?

回答1:

Macros are just replaced by their definition. When you #define k 1024; and write if(k==1024)... what the compiler actually sees is:

if(1024; == 1024) ...

which doesn't compile.

The compiler doesn't complain because sometimes you may actually want to add a semicolon (; is called semicolon, not colon, which is :) to your macro.