Michal
Michal

Reputation: 15669

Xcode compiler not accepting ternary operator

I am using this one tiny bit of code:

CGFloat gradientLocations[2] = {1.0f, 0.0f};

which unfortunatelly has a bug, because the gradient points at one direction and is not correctly rotated. So I wanted to fix it with azimuth like this:

CGFloat gradientLocations[2] = self.isAzimuthDown ? {0.0f, 1.0f} : {1.0f, 0.0f};

But I keep getting error that I am missing ":", which I don't believe I am...my question is - what is wrong with it and how to fix it?

Upvotes: 1

Views: 72

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726499

The language does not support conditional expressions in array initializers. You can fix this by using memcpy, or by using conditional expressions inside a single initializer for each individual element:

Using memcpy (demo):

CGFloat gradientLocations[2];
memcpy(gradientLocations, self.isAzimuthDown ? (CGFloat[]){0.0f, 1.0f} : (CGFloat[]){1.0f, 0.0f}, sizeof(gradientLocations));

Using conditional in scalar expressions (demo):

CGFloat gradientLocations[2] = {self.isAzimuthDown ? 0.0f : 1.0f, self.isAzimuthDown ? 1.0f : 0.0f};

Upvotes: 1

Related Questions