Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the result of an assignment as a condition without parentheses

I have this inside a custom UIActionSheet class

if (otherButtonTitles != nil) {
    [self addButtonWithTitle:otherButtonTitles];
    va_list args;
    va_start(args, otherButtonTitles);
    NSString * title = nil;
    while(title = va_arg(args,NSString*)) { // error here
        [self addButtonWithTitle:title];
    }
    va_end(args);
}

I have this error

! using the result of an assignment as a condition without parentheses

pointing to this line

while(title = va_arg(args,NSString*)) {

why is that?

thanks.

like image 795
Duck Avatar asked Dec 06 '10 18:12

Duck


3 Answers

This is probably not an error as you said, it's a warning.

The compiler is warning you that you should surround assignments within parentheses when it is within a conditional to avoid the ol' assignment-when-you-mean-comparison mistake.

To get past this rather pedantic compiler warning, you can simply surround the assignment within another pair of parentheses:

while((title = va_arg(args,NSString*))) {
//...
}
like image 133
Jacob Relkin Avatar answered Nov 01 '22 19:11

Jacob Relkin


It should be a warning and not an error. It's trying to warn in case you're using = but you meant ==.

In this case, you're not meaning to use == because you're calling va_arg() multiple times to iterate through otherButtonTitles and assigning it to the temp var title, so just add another set of parentheses. The warning will go away.

while((title = va_arg(args,NSString*))) {
like image 8
BoltClock Avatar answered Nov 01 '22 18:11

BoltClock


compiler thinks that you're doing assignment by mistake, hence suggesting this error. You should wrap your statement into ONE MORE PAIR of parenthesis like this:

while((title = va_arg(args,NSString*)))

Then compiler first will evaluate the assignment, then the result of that assignment will be passed into the while condition

like image 2
Eimantas Avatar answered Nov 01 '22 19:11

Eimantas