views:

136

answers:

1

Hi!

REAL newbie here to Objective C and Cocoa.

I have this 'if statement'

if (cardCount = 2)
   UIImage *image = [UIImage imageNamed: @"Card 2.png"];

This gives me "error: syntax error before '*' token"

Why? The UIImage line works fine by itself.

I'd appreciate a pointer to what I've done wrong.

Thanks Paul

+14  A: 

First of all, the condition should read cardCount == 2 but that's not the cause of that error. The problem is, variable declaration and initialization does not count as a statement in language grammar. It's a declaration. You cannot have a declaration as the body of if, while, etc. (by the way, a block is considered a statement, which might contain declarations, so that's a different thing). After all, there's no use to it as it'll fall out of scope immediately so it's disallowed.

UIImage *image;
if (cardCount == 2)
   image = [UIImage imageNamed: @"Card 2.png"];

If you just need that variable in the if statement (I doubt this is what you want though):

if (cardCount == 2) {
   UIImage* image = [UIImage imageNamed: @"Card 2.png"];
   // code to use `image`
}
Mehrdad Afshari
Thanks! That did the trick! I wish I could vote but this is my first question!