Parul
Parul

Reputation: 25

Why is conditional operator giving desired result for first statement but not for second?

Second one is giving some sky blue color

#define GREEN_COLOR           0x69BC63
#define RED_COLOR             0xCC4C46
#define UIColorFromRGB(rgbValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]

//Working
[amount setTextColor: [[trans amount] intValue]>=0 ? UIColorFromRGB(GREEN_COLOR):UIColorFromRGB(RED_COLOR)];

//Not working
[amount setTextColor: UIColorFromRGB([[trans amount] intValue]>=0 ? GREEN_COLOR:RED_COLOR)];

Upvotes: 0

Views: 75

Answers (1)

Jeffery Thomas
Jeffery Thomas

Reputation: 42588

You have a parentheses problem.

#define UIColorFromRGB(rgbValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]

can be redone as

#define UIColorFromRGB(rgbValue) [UIColor colorWithRed:((float)(((rgbValue) & 0xFF0000) >> 16))/255.0 green:((float)(((rgbValue) & 0xFF00) >> 8))/255.0 blue:((float)((rgbValue) & 0xFF))/255.0 alpha:1.0]

which should fix your issue, but makes the macro even harder to read.


You really should consider making this a proper function instead of a macro.

At the very least use a statement expression so rgbValue is evaluated only once.

#define UIColorFromRGB(rgbValue) ({ unsigned v = rgbValue; [UIColor colorWithRed:((float)((v & 0xFF0000) >> 16))/255.0 green:((float)((v & 0xFF00) >> 8))/255.0 blue:((float)(v & 0xFF))/255.0 alpha:1.0]; })

Upvotes: 2

Related Questions