Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly define constants [duplicate]

Tags:

c

objective-c

Possible Duplicate:
Constants in Objective C

I'm designing a controller and I'm gonna need some constants inside it (locally, just for that controller). Looking at some sample code provided by Apple, I can see these lines:

#import "Constants.h"

#define kTextFieldWidth 260.0

static NSString *kSectionTitleKey = @"sectionTitleKey";
static NSString *kSourceKey = @"sourceKey";
static NSString *kViewKey = @"viewKey";

const NSInteger kViewTag = 1;

Can anyone explain to me what the difference between them is? Which style should I use? Are they dependent on the type of object/value you assign to them? Meaning use: static NSString * for strings, #define for floats and NSInteger for integers? How do you make the choice?

like image 984
Hidden Avatar asked Jun 20 '11 18:06

Hidden


People also ask

Which is the correct way to declare a constant?

You use the Const statement to declare a constant and set its value. By declaring a constant, you assign a meaningful name to a value. Once a constant is declared, it cannot be modified or assigned a new value. You declare a constant within a procedure or in the declarations section of a module, class, or structure.

How do you define a constant in Java?

A constant is a variable whose value cannot change once it has been assigned. Java doesn't have built-in support for constants. A constant can make our program more easily read and understood by others. In addition, a constant is cached by the JVM as well as our application, so using a constant can improve performance.

Which is the best way to describe the constant literals in a class?

The public|private static final TYPE NAME = VALUE; pattern is a good way of declaring a constant.


1 Answers

The #define keyword is a compile time directive that causes the define'd value to be directly injected into your code. It is global across the entire program and all linked libraries. So you can strike that off the list, based on your desire to create a constant for the controller only.

The main difference between static and const is that static variables can be changed after initialization, const ones cannot. If you want to be able to modify your variable after initialization then you should use the static keyword.

Hope that helps.

like image 150
Perception Avatar answered Sep 20 '22 04:09

Perception