Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enums in Objective-C VS C

SA, What I know is that Objective-C is a strict superset of C..

But when I've tried a very simple enum example that I used to use in C, it didn't work in objective C,

Here's the code:

#import <Foundation/Foundation.h>

int main(void)
{
    typedef enum 
    {
        SUN, MON, TUES
    }DAYS;

    DAYS d = MON;

    NSLog(@"%@", d);

    return 0;
}

#include <stdio.h>

int main(void)
{
    typedef enum 
    {
        SUN, MON, TUES
    }DAYS;

    DAYS d = MON;

    printf("%d\n", d);

    return 0;
}

In C, it works perfectly, but in objective-c (I am using GNUstep on WIN) it crashes when executing (no compile-time errors)

Can anyone tell me why?

like image 232
Muhammad Hewedy Avatar asked Nov 29 '22 10:11

Muhammad Hewedy


2 Answers

%@ is an object specifier and enums are an int (signed or unsigned). To print an enum in Objective-C you need to use %d in your NSLog.

NSLog(@"%d", d);

Your original example was crashing because it expected d to be an object so it would try and send the description message to an object residing at memory address 1 (the value of MON).

like image 157
Joe Avatar answered Dec 04 '22 16:12

Joe


Try this

int main(void)
{
    typedef enum 
    {
        SUN, MON, TUES
    }DAYS;

    DAYS d = MON;

    NSLog(@"%d", d); //here is your mistake happened, because enum return values are integers.

    return 0;
}

Hope this help

like image 28
Asish AP Avatar answered Dec 04 '22 17:12

Asish AP