Error: expected expression on line using #defined

2019-02-25 00:12发布

问题:

I'm doing this

if ([resourceCompletionReward objectAtIndex:experienceD] != 0) {

But Xcode is giving me an error:

Expected expression

I've defined experienceD as

#define experienceD 0;

What am I doing wrong?

回答1:

The semicolon shouldn't be there.

#define experienceD 0

will compile just fine.

Also it's a good practice to name constants with an UPPER_CASE_NOTATION like this.

For completeness I will add that Apple suggests (from the Coding Guidelines for Cocoa)

In general, don’t use the #define preprocessor command to create constants. For integer constants, use enumerations, and for floating point constants use the const qualifier

and also

You can use const to create an integer constant if the constant is unrelated to other constants; otherwise, use enumeration

So in your specific case it would be better to define your constant as

static const int ExperienceD = 0;


回答2:

You shouldn’t use #define to define constants. All that #define does is text replacement, so in your case the compiler sees

if ([resourceCompletionReward objectAtIndex:0;] != 0) {

and complains about the ; where it shouldn’t be.

This can be especially troublesome if you want to calculate your constant:

#define CONSTANT 1 + 2
int y = 2 * CONSTANT;

The compiler does simple text replacement so you get

int y = 2 * 1 + 2;

which is not really the expected value. To work around this you can remember to add parentheses around each #defined constant.

A better way to define constants is to use const variables:

static const int experienceD = 0;

If you define lots of constants with consecutive integer values you also can use an enum.

enum {
    experienceD = 0;
};