Using the result of an assignment as a condition without parentheses
I have this inside a custom UIActionSheet class
if (otherButtonTitles != nil) {
[self addButtonWithTi开发者_如何学Pythontle: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.
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*))) {
//...
}
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*))) {
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
It does seem a little picky, but have you tried:
while((title = va_arg(args,NSString*)) != NULL)
?
精彩评论