4

In Xcode, the compiler is complaining about the following cast:

CGFloat width = 5.6f; NSInteger num = (NSInteger)floor(width);

Saying "cast from function call of type 'double' to non-matching type 'NSInteger' (aka 'int')"

One workaround would be to simply cast the CGFloat to NSInteger which truncates but I want to make the code clear/easy to read by explicitly flooring. Is there a function for flooring that returns an int? Or some other (clean) way of doing this?

My compiler settings under "Apple LLVM 6.0 - Compiler Flags", in "Other C Flags", I have -O0 -DOS_IOS -DDEBUG=1 -Wall -Wextra -Werror -Wnewline-eof -Wconversion -Wendif-labels -Wshadow -Wbad-function-cast -Wenum-compare -Wno-unused-parameter -Wno-error=deprecated

Thanks!

Dave
  • 534
  • 1
  • 5
  • 14
  • I tried the code and it works perfectly fine without any errors. Did you try compiling it again? This can sometimes help. – Palle Jul 28 '15 at 21:25
  • I think this may have to do with compiler settings--mine are on a fairly strict setting (and must stay that way). – Dave Jul 28 '15 at 23:40
  • 1
    i tried the code you specified and there were no errors. What settings do you have? – jacob bullock Jul 29 '15 at 00:43
  • In "Apple LLVM 6.0 - Custom Compiler Flags" in my Build Settings I have: **-O0 -DOS_IOS -DDEBUG=1 -Wall -Wextra -Werror -Wnewline-eof -Wconversion -Wendif-labels -Wshadow -Wbad-function-cast -Wenum-compare -Wno-unused-parameter -Wno-error=deprecated** – Dave Jul 29 '15 at 01:00

2 Answers2

9

Okay, as you mentioned strict compiler settings, I tried again and found the solution. The compiler warning is because you are trying to cast the floor function to a NSInteger value and not the returned value.

To solve this, all you have to do, is to put floor(width) in parentheses like this:

NSInteger num = (NSInteger) (floor(width));

or save the result of the floor operation to another CGFloat and cast the new variable to NSInteger

CGFloat floored = floor(width);
NSInteger num = (NSInteger) floored;
Palle
  • 11,511
  • 2
  • 40
  • 61
4

Use floorf() for floats. So NSInteger num = (NSInteger)floorf(width);

More information CGFloat-based math functions?

Community
  • 1
  • 1
TheSD
  • 873
  • 5
  • 17
  • floorf returns a float, I get the same error: "cast from function call of type 'float' to non-matching type 'NSInteger' (aka 'int')" – Dave Jul 28 '15 at 23:38
  • Weird. In C, it is perfectly legal to cast a `float` into an `int`... or isn't it? – Nicolas Miari Jul 29 '15 at 01:13
  • This is because of my compiler settings--I can't cast a method's return value to another type directly. – Dave Jul 29 '15 at 02:12