TExcelTAD
Home › Objective-C › C Foundations: Types & Operators

C Foundations: Types & Operators

Because Objective-C is a superset of C, the "small stuff" (numbers, arithmetic, comparisons) is exactly C. This lesson and the next two are a quick recap. If you already know C, skim them for the Objective-C additions: BOOL, NSInteger and friends.

Variables and basic types

A variable is declared with its type first. C types are value types: the variable holds the number itself.

objc · try it yourself
#import <Foundation/Foundation.h>

int main(void) {
    @autoreleasepool {
        int apples = 7;               // whole number
        double price = 0.35;          // floating point, ~15 digits
        float weight = 1.5f;          // floating point, ~7 digits
        char initial = 'K';           // a single byte character
        BOOL inStock = YES;           // Objective-C's boolean: YES or NO

        NSLog(@"%d apples at %.2f each", apples, price);
        NSLog(@"weight %.1f kg, initial %c", weight, initial);
        NSLog(@"in stock: %d", inStock);
        NSLog(@"total: %.2f", apples * price);
    }
    return 0;
}
7 apples at 0.35 each
weight 1.5 kg, initial K
in stock: 1
total: 2.45

The Foundation type aliases are what you see in Apple APIs:

Type What it is
NSInteger signed integer, 64-bit on 64-bit systems
NSUInteger unsigned integer (counts, indexes), same size
BOOL boolean, values YES and NO
CGFloat double on 64-bit Apple systems (used for graphics, from Core Graphics)
NSTimeInterval double, a number of seconds

BOOL prints as 1 or 0 with %d. To print a word, use the ternary operator: inStock ? @"YES" : @"NO".

Sizes

sizeof tells you how many bytes a type takes:

objc · try it yourself
#import <Foundation/Foundation.h>

int main(void) {
    @autoreleasepool {
        NSLog(@"char:       %zu byte", sizeof(char));
        NSLog(@"int:        %zu bytes", sizeof(int));
        NSLog(@"double:     %zu bytes", sizeof(double));
        NSLog(@"NSInteger:  %zu bytes", sizeof(NSInteger));
        NSLog(@"pointer:    %zu bytes", sizeof(NSString *));
        NSLog(@"int range:  %d to %d", INT_MIN, INT_MAX);
    }
    return 0;
}
char:       1 byte
int:        4 bytes
double:     8 bytes
NSInteger:  8 bytes
pointer:    8 bytes
int range:  -2147483648 to 2147483647

%zu is the specifier for size_t, the type sizeof returns.

Arithmetic

Operator Meaning
+ - * / add, subtract, multiply, divide
% remainder (integers only)
++ -- increment / decrement by one
+= -= *= /= compound assignment

The classic trap: dividing two integers throws away the fraction. Convert one side to double first.

objc · try it yourself
#import <Foundation/Foundation.h>

int main(void) {
    @autoreleasepool {
        int pizzas = 7;
        int people = 2;

        NSLog(@"integer division: %d", pizzas / people);
        NSLog(@"remainder: %d", pizzas % people);
        NSLog(@"real division: %.1f", (double)pizzas / people);

        int score = 10;
        score += 5;
        score *= 2;
        score--;
        NSLog(@"score: %d", score);

        int counter = 5;
        int a = counter++;   // use, then increment
        int b = ++counter;   // increment, then use
        NSLog(@"a=%d b=%d counter=%d", a, b, counter);
    }
    return 0;
}
integer division: 3
remainder: 1
real division: 3.5
score: 29
a=5 b=7 counter=7

Comparison and logic

Comparisons (== != < > <= >=) produce 1 (true) or 0 (false). Combine them with && (and), || (or) and ! (not). && and || short-circuit: the right side is only evaluated when needed.

objc · try it yourself
#import <Foundation/Foundation.h>

int main(void) {
    @autoreleasepool {
        NSInteger age = 19;
        BOOL hasTicket = YES;

        BOOL adult = age >= 18;
        BOOL canEnter = adult && hasTicket;
        BOOL needsHelp = !hasTicket || age < 12;

        NSLog(@"adult: %@", adult ? @"YES" : @"NO");
        NSLog(@"can enter: %@", canEnter ? @"YES" : @"NO");
        NSLog(@"needs help: %@", needsHelp ? @"YES" : @"NO");
    }
    return 0;
}
adult: YES
can enter: YES
needs help: NO

Constants

const makes a variable read-only, and #define creates a text-replacement macro. In Objective-C code you often see string constants declared with static NSString * const:

objc
static const NSInteger MaxRetries = 3;
static NSString * const ErrorDomain = @"com.example.app";
#define SECONDS_PER_DAY (24 * 60 * 60)

Note: Prefer const over #define for values: constants have a type, the compiler checks them, and debuggers can show them.

Test yourself

What does 7 / 2 evaluate to when both are int?

  1. 3.5
  2. 3
  3. 4
  4. an error

What are the two values of Objective-C's BOOL?

  1. true / false
  2. YES / NO
  3. ON / OFF
  4. 1.0 / 0.0

After int c = 5; int x = c++;, what are x and c?

  1. x=5, c=6
  2. x=6, c=6
  3. x=5, c=5
  4. x=6, c=5