Constants in Objective-C

Go supports constants of character, string, boolean, and numeric values.

#import <Foundation/Foundation.h>
#import <math.h>

const NSString *s = @"constant";

int main (int argc, const char * argv[]) {
    @autoreleasepool {
        NSLog(@"%@", s);

        const int n = 500000000;
        NSLog(@"%d", n);

        const double d = 3e20 / n;
        NSLog(@"%e", d);
        NSLog(@"%lld", (int64_t)d);

        NSLog(@"%f", sin(n));
    }
    return 0;
}

const declares a constant value. This can be a character, string, boolean, or numeric value.

In the main function, we first print the string constant s.

NSLog(@"%@", s);

Constants can appear anywhere a variable can. We declare an integer constant n and print it.

const int n = 500000000;
NSLog(@"%d", n);

Constant expressions can perform arithmetic with arbitrary precision.

const double d = 3e20 / n;
NSLog(@"%e", d);
NSLog(@"%lld", (int64_t)d);

A numeric constant has no type until it’s given one, such as by an explicit conversion. Here, we convert the double constant to an int64_t.

NSLog(@"%lld", (int64_t)d);

A number can be given a type by using it in a context that requires one, such as a variable assignment or function call. For example, sin expects a double.

NSLog(@"%f", sin(n));

To run the program, compile it with clang and then execute the binary.

$ clang main.m -framework Foundation -o main
$ ./main
constant
500000000
6.000000e+11
600000000000
-0.284704

Now that we can run and understand basic Objective-C constants, let’s learn more about the language.