Search code examples
objective-csyntaxternary

Does the ternary operator work in constant definition?


Why do I get a compiler error when using a ternary operator in the assignment of a CGSize const like this?

CGSize const ksizeSmall = SOME_BOOLEAN_VARIABLE ? {187, 187} : {206, 206};

it does work like this...

CGSize const ksizeSmall = {187, 187};

however, I want to add a boolean expression to evaluate whether I should use one size vs. the other size. I don't want to use if / else because I have a long list of CGSize to set specifically for different purposes.


Solution

  • {187, 187} and {206, 206} aggregates are valid as an initialization expressions, but not as a general-purpose expressions*. That is why a ternary operator does not allow it.

    If you are making an initializer for a local constant, you could use CGSizeMake:

    CGSize const ksizeSmall = SOME_BOOLEAN_VARIABLE ? CGSizeMake(187, 187) : CGSizeMake(206, 206);
    

    If SOME_BOOLEAN_VARIABLE is a compile-time constant expression, you could use conditional compilation instead:

    #if SOME_BOOLEAN_VARIABLE
    CGSize const ksizeSmall = {187, 187};
    #else
    CGSize const ksizeSmall = {206, 206};
    #endif
    

    * gcc compiler has a C language extension that offers a special syntax for doing this. It was available in Objective-C as well. However, this extension is not part of the language.