views:

121

answers:

4

Hi, everyone,

I want to ask a question about the objective C or may be the C language. I want to ask what is the meaning of the following code of #define? Is it like to declare a variable? Thank you.

#define kMountainNameString         @"name"
#define kMountainHeightString           @"height"
#define kMountainClimbedDateString      @"climbedDate"
+1  A: 

The preprocessor replaces all occurences of kMountainNameString with @"name" before compiling begins.

Plumenator
+7  A: 

It's a simple text substitution macro. Works the same as in C, C++.

Where kMountainNameString appears the compiler will "paste in" @"name". Technically speaking this occurs before the compiler by a mechanism called the preprocessor.

seand
Its the preprocessor that does the substitution. The compiler will not see any #defines.
codaddict
yep way back when (maybe still today) preprocessing was done by a separate independent tool.
seand
thank you for all the reply. and I want to ask what is the data type of those 3 elements?
Questions
The ones you have written there are NSString literals, but #define does not take types or do typing. Think of it as a search-and-replace that gets run on your source code before it is compiled. kMountainNameString will be replaced by @"name", but the preprocessor doesn't care at all about types, nor does it do any type checking.
Jergason
NString-s. Note that preprocessing is simple and dumb. Overuse is discouraged, especially in C++. Preprocessors don't know anything about types and underlying language syntax.
seand
+2  A: 

#define is a preprocessor directive inherited from C that takes the form

#define identifier value

In general, it is used to tell the preprocessor to replace all instances of identifier in the code with the given text before passing it on to the compiler. Identifiers can also be defined without values to be used as compiler flags to prevent multiple definitions of the same variables, or to branch on machine details that will not change during execution. For example, to pass different code to the compiler based on the architecture of your processor you could do something like:

#ifdef INTEL86
//some 32-bit code
#else
//some 64-bit code
#endif

When assigning values in these definitions, it's often a good idea to surround the value with parentheses so as to preserve it as one unit, regardless of the context it exists in.

For example, #define FOO 3 + 7 has a different result than #define FOO (3 + 7) on the result of the following line, due to the order of arithmetic operations:

a = 3 * FOO

See this link for more details on preprocessor directives in general or this link for information more focused on Objective C.

psicopoo
A: 

#define is the preprocessor directive in c and c++ language.

It is used to define the preprocessor macros for the texts. The #define is used to make substitutions throughout the file in which it is located.

#define <macro-name> <replacement-string>
Kumar Alok