Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constants by another name

First off, I've seen this question and understand why the following code doesn't work. That is not my question.

I have a constant, which is declared like;

//Constants.h
extern NSString * const MyConstant;

//Constants.m
NSString * const MyConstant = @"MyConstant";

However, in certain contexts, it's more useful to have this constant have a much more descriptive name, like MyReallySpecificConstant. I was hoping to do:

//SpecificConstants.h
extern NSString * const MyReallySpecificConstant;

//SpecificConstants.m
#import "Constants.h"
NSString * const MyReallySpecificConstant = MyConstant;

Obviously I cannot do this (which is explained in the linked question above).

My question is:

How else (besides something like #define MyReallySpecificConstant MyConstant) can I provide a single constant under multiple names?

like image 579
Dave DeLong Avatar asked May 26 '10 02:05

Dave DeLong


1 Answers

In general, the compiler will fold identical string constants into the same strings unless you tell it not to. Even though you cannot initialize one constant with another, initializing them both with the same value will have the same net effect.

//Constants.h
extern NSString * const MyConstant;
extern NSString * const MyOtherConstant;

//Constants.m
#define MyConstantValue "MyConstant"
NSString * const MyConstant = @MyConstantValue;
NSString * const MyOtherConstant = @MyConstantValue;

You hide the #define in one source file instead of in a header. You only have to change the value in one place. You have two names for one constant. Of course, in your scenario with constants defined in multiple files, you would have to have the #define accessible to those source files.

like image 139
drawnonward Avatar answered Oct 17 '22 15:10

drawnonward