2

I wrote a method tha uses myarray, defined in the same class. When I use count it always returns 0. When I use:

printf("%d", [myarray count]);

compiler says:

Format '%d' expetcs type 'int', but argument 2 has type 'NSUInteger'

why?

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
thepepp
  • 304
  • 1
  • 3
  • 15

1 Answers1

5

You should use %lu instead of %d. The compiler checks your format string against the parameters that you are passing to printf, sees that you are passing an unsigned but print it as a signed integer, and issues a warning. The warning indicates that for numbers greater than or equal to 2^31 printf would output a large negative number, when the data type implies a different semantic, namely, a large positive integer.

EDITED in response to comments by Josh Caswell and thepepp

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • 3
    The [docs say](http://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Strings/Articles/formatSpecifiers.html#//apple_ref/doc/uid/TP40004265-SW5) to use `%lu` for `NSUInteger`. – jscs Jan 10 '12 at 19:53
  • @JoshCaswell @theapp Thanks for the comments! I did not realize that the size of `NSUInteger` changes based on the platform setting. I edited the answer. – Sergey Kalinichenko Jan 10 '12 at 20:12
  • 2
    Not only should you use `%lu` but you should also cast your `NSUInteger` to `(unsigned long)`. Typically you'll find that omitting the cast is fine, but for strict correctness you should have it, and the [String Format Specifiers](http://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/Strings/Articles/formatSpecifiers.html#//apple_ref/doc/uid/TP40004265-SW1) guide tells you to perform the cast. – Lily Ballard Jan 10 '12 at 20:22