articles

Home / DeveloperSection / Articles / Objective C : Constants

Objective C : Constants

Tarun Kumar3324 08-Jul-2015

Previously we learn Blocks creation in Objective C:Objective-C : Blocks 

The constants refer to fixed values that the program may not alter during its execution. These fixed values are also called literals.

Constants can be of any of the basic data types like an integer constant, a floating constant, a character constant, or a string literal. There are also enumeration constants as well.

When you’re building an app you usually need some values to remain the same for the whole runtime of the app. Instead of using those values everywhere inside your app it is better to define a constant 

The constants are treated just like regular variables except that their values cannot be modified after their definition. 

Integer literals 

An integer literal can be a decimal, octal, or hexadecimal constant. A prefix specifies the base or radix: 0x or 0X for hexadecimal, 0 for octal, and nothing for decimal.

An integer literal can also have a suffix that is a combination of U and L, for unsigned and long, respectively. The suffix can be uppercase or lowercase and can be in any order.

Following are other examples of various types of Integer literals:

85            /* decimal */

0213       /* octal */

0x4b       /* hexadecimal */

30           /* int */

30u        /* unsigned int */

30l         /* long */

30ul       /* unsigned long */

 

Floating-point literals

A floating-point literal has an integer part, a decimal point, a fractional part, and an exponent part. You can represent floating point literals either in decimal form or exponential form.

 

Here are some examples of floating-point literals:


3.14159           /* Legal */

314159E-5L    /* Legal */

510E                /* Illegal: incomplete exponent */

210f                 /* Illegal: no decimal or exponent */

.e55                 /* Illegal: missing integer or fraction */

 

Character constants

 

A character literal can be a plain character (e.g., 'x'), an escape sequence (e.g., '\t'), or


a universal character (e.g., '\u02C0').

 

Escape sequence
Meaning

 \\

\ character

 \'

' character

 \"

" character

 \?

? character

 \a

Alert or bell

 \b

Backspace

 \f

Form feed

 \n

Newline

 \r

Carriage return

 \t

Horizontal tab

 \v

Vertical tab

 \ooo

Octal number of one to three digits

 \xhh . . .

Hexadecimal number of one or more digits

 

Following is the example to show few escape sequence characters:

#import< Foundation/Foundation.h>

int main()

{

   NSLog(@"Hello\tWorld\n\n");

   return 0;

}

 

String literals

 

String literals or constants are enclosed in double quotes "". A string contains characters that are similar to character literals: plain characters, escape sequences, and universal characters.

You can break a long line into multiple lines using string literals and separating them using whitespaces.

Here are some examples of string literals. All the three forms are identical strings.

"hello, dear"

"hello, \

dear"

"hello, " "d" "ear"

 

There are two simple ways in C to define constants:


1.  Using const keyword.


2.  Using #define preprocessor.

 

The const Keyword 

If you do want to have a constant global then you should use extern. In the .h file


you should define the constant like this:

extern NSString * const MY_ID;

 

And in the .m file you would actually give it a value:

NSString * const MY_ID = @"2A3D";

 

This way your API interface will be nice and pretty, you’re not exposing the internals of your class to the world. If you have constants that are used in lots of classes all over the app then it makes sense to have a separate .h and .m file just for defining these constants. This way whenever you need to change the value of one of your constants you know where to look.

You can use const prefix to declare constants with a specific type as follows:

const type variable = value;

 

Following example explains it in detail: 

#import< Foundation/Foundation.h>

int main()

{

   NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

   const int  LENGTH = 10;

   const int  WIDTH  = 5;

   const char NEWLINE = '\n';

   int area;    

   area = LENGTH * WIDTH;

   NSLog(@"value of area : %d", area);

   NSLog(@"%c", NEWLINE);

   [pool drain];

   return 0;

}


When the above code is compiled and executed, it produces the following result:


2015-07-09 03:30:46.801 demo[31083] value of area : 50

2015-07-09 03:30:46.803 demo[31083] 


The #define Preprocessor

 

Define is used in order to ease the code readability and future modifications. When using a define, you only mask a value behind a name. Hence when working with a rectangle you can define width and height with corresponding values. Then in the code, it will be easier to read since instead of numbers there will be names. If later you decide to change the value for the width you would only have to change it in the define instead of a boring and dangerous find/replace in your whole file. When compiling, the preprocessor will replace all the defined name by the values in the code. Hence, there is no time lost using them.

You can do something like this: 

#define MAX_NUMBER_OF_ROWS 10

 

The value of MAX_NUMBER_OF_ROWS will always be 10 so this sounds like our definition of a constant. This is not an actual constant. It’s called a preprocessing macro because before compile time all the occurrences of MAX_NUMBER_OF_ROWS will be replaced by the actual value, 10 in our case. You’ve probably noticed that we didn’t specify a type for MAX_NUMBER_OF_ROWS. However, because the value gets replaced before compile time, the compiler will complain if you try to assign an int to an NSString for example. You will also get an error if you try to assign a value toMAX_NUMBER_OF_ROWS. So although this is not a constant it does make sure the value is the same and that you have a nice significant name for that value. 

Example: 
#define AbsoluteValue(x) (x >= 0 ? x : -x)

 

Your rationale in this case is, “This is just a simple check. If I put it in a function, I


waste the overhead of calling another function.” Doesn’t work out that way in


practice, though. First, this code can cause subtle issues like:

int b = 4;
int a = AbsoluteValue(b++);

 

Which evaluates to:

int b = 4;
int a = (b++ >= 0 ? b++ : -b++);

Which makes a equal to 5 and b equal to 6. Yikes. Also, the compiler is purely


smart, so when it sees a function like,   

int AbsoluteValue(int x) 
{
    return (x >= 0 ? x : -x);
}

it’ll inline the function, which means the function doesn’t actually get called, but its code gets executed.

 

Following is the form to use #define preprocessor to define a constant:


#define identifier value

Following example explains it in detail:

#import< Foundation/Foundation.h>

#define LENGTH 10  

#define WIDTH  5

#define NEWLINE '\n'

int main()

{

   NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

   int area;

   area = LENGTH * WIDTH;

   NSLog(@"value of area : %d", area);

   NSLog(@"%c", NEWLINE);

    [pool drain];

   return 0;

}

When the above code is compiled and executed, it produces the following result:


2015-07-09 03:35:19.702 demo[731] value of area : 50

2015-07-09 03:35:19.703 demo[731]

[ Note that it is a good programming practice to define constants in CAPITALS. ] 

 


Next, we will learn about : Objective-C : Numbers


Updated 30-Nov-2017

Leave Comment

Comments

Liked By