1

Please do tell me what does an exclamation mark mean before a NSString

NSString *theString;
if (!theString);

cheers;

Ramuel
  • 59
  • 8

2 Answers2

3

! is the boolean negation operation. It inverts YES to NO and vice-versa. NO is always equal to 0, while YES is any non-zero value, and as Jeremiah points out, a nil pointer is one that is set to 0x0, or decimal 0. Any pointer that isn't nil has a boolean value of TRUE. So, (!theString) is equivalent to (theString == nil).

Thomson Comer
  • 3,919
  • 3
  • 30
  • 32
  • "Any pointer that isn't nil has a boolean value of TRUE." I don't think that's true since this will print FALSE. NSLog(@"2 == TRUE? %@", 2 == TRUE ? @"TRUE" : @"FALSE") – Tobias Feb 13 '11 at 07:28
  • You're right about that, and that's interesting. I'm going to have to reconsider some assumptions and research this. Thanks. :) – Thomson Comer Feb 13 '11 at 15:52
  • I did some experiments and here's what I determined. Any non-zero value evaluates as true in a conditional statement. However the constants TRUE, true, and YES are specifically set to 1. So `2 != TRUE` but `if( 2 ){NSLog(@"It was true";}else{NSLog(@"It wasn't true";}` will print `It was true`. – Thomson Comer Apr 26 '11 at 20:10
2

The ! symbol here (and in front of any expression whose type is a pointer) returns a true (1) result if the pointer is NULL and false (0) otherwise. The !theString expression is then just a short way of saying theString == NULL.

Jeremiah Willcock
  • 30,161
  • 7
  • 76
  • 78
  • so correct me if im wrong, the expression in the parenthesis evaluates to either 0 or 1, then `(!)` negates it? – Ramuel Feb 13 '11 at 06:22