Bartłomiej Semańczyk Bartłomiej Semańczyk - 4 months ago 9
Objective-C Question

Why when I use #define for int I need to wrap them in brackets?

This is my example I've found:

#define kNumberOfViews (37)
#define kViewsWide (5)
#define kViewMargin (2.0)


Why it cannot be like that?

#define kNumberOfViews 37
#define kViewsWide 5
#define kViewMargin 2.0


And what means
k
in front? Is there a some guide for it?

Answer

It is not really required in your example, but the use of parenthesis in defines is a useful approach to make sure your define states exactly what you mean in the context of the define and protects it from side effects when used in code.

E.g

#define VAR1 40
#define VAR2 20
#define SAVETYPING1 VAR1-VAR2
#define SAVETYPING2 (VAR1-VAR2)

Then in your code

foo(4*SAVETYPING1);  // comes out as foo(140)

Is not the same as

foo(4*SAVETYPING2); // comes out as foo(80)

As for what the k prefix means. It is used for constants. Plenty of discussion here on the origins:

Objective C - Why do constants start with k