Bartłomiej Semańczyk
Bartłomiej Semańczyk

Reputation: 61832

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?

Upvotes: 0

Views: 887

Answers (3)

Jakub Vano
Jakub Vano

Reputation: 3873

#define SOME_VALUE 1234

It is preprocessor directive. It means, that before your code is compiled, all occurrences of SOME_VALUE will be replaced by 1234. Alternative to this would be

const int kSomeValue = 1234;

For discussion about advantages of one or the other see #define vs const in Objective-C

As for brackets - in more complex cases they are necessary exactly because preprocessor makes copy-paste with #define. Consider this example:

#define BIRTH_YEAR   1990
#define CURRENT_YEAR 2015
#define AGE CURRENT_YEAR - BIRTH_YEAR

...
// later in the code
int ageInMonths = AGE * 12;

Here one might expect that ageInMonths = 25 * 12, but instead it is computed as ageInMonths = 2015 - 1990 * 12 = 2015 - (1990 * 12). That is why correct definition of AGE should have been

#define AGE (CURRENT_YEAR - BIRTH_YEAR)

As for naming conventions, AFAIK for #define constants capital cases with underscores are used, and for const constants camel names with leading k are used.

Upvotes: 2

Rory McKinnel
Rory McKinnel

Reputation: 8014

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

Upvotes: 5

Tim
Tim

Reputation: 2912

k is just a hungarian notation convention to indicate that that is a constant value. Personally I find it dumb, but it is a convention that many people follow. It isn't required for the code to work at all.

I am not sure why the examples you saw had parens around them, but there is no need to have parentheses around #define values.

Upvotes: -2

Related Questions