Vinícius
Vinícius

Reputation: 23

Weird division results (C++ / Xcode)

I'm kinda new here, so please forgive me if I'm doing something wrong. I did a little search before posting this but got no results. So on to the topic: I was getting an error when an AI agent was behaving strangely, so I drafted a few printf's to take a look at what was going on.

It turned out to be a wrong result of a simple division:

#define WORLD_HEIGHT 42
#define VIEWPOINT_CONSTANT 9

printf ("%d/%d=%d\n", WORLD_HEIGHT, VIEWPOINT_CONSTANT, WORLD_HEIGHT/VIEWPOINT_CONSTANT);

Output:

42/9=6

Then I did the following just to check the compiler etc.:

printf ("%d/%d=%d\n", 42, 9, 42/9);

Output:

42/9=4        

Not sure if this is an Xcode bug or something in C++ (though I doubt it's the latter, then again the former is pretty unlikely too). In order to make sure I wasn't overlooking anything, I even put the constants themselves in the printf's.

If anyone has a clue as to what may be the cause of this problem or how to solve it (while still keeping the #define's instead of replacing them with numbers), it would be greatly appreciated.

Cheers!

Upvotes: 2

Views: 246

Answers (1)

Paul R
Paul R

Reputation: 212949

My guess is that you're not showing us real code and that what you actually have is something like this:

#define WORLD_HEIGHT 42
#define VIEWPOINT_CONSTANT 8+1

printf ("%d/%d=%d\n", WORLD_HEIGHT, VIEWPOINT_CONSTANT, WORLD_HEIGHT/VIEWPOINT_CONSTANT);

This will give the result you are seeing because 42/8+1 is not the same as 42/9 - it's evaluated as (42/8)+1, which is 5+1 and so you will get a value of 6 rather than 4. This can be fixed by using parentheses to enforce the required order of evaluation, i.e.

#define VIEWPOINT_CONSTANT (8+1)

or better still, use a more appropriate method for defining constants rather than preprocessor macros, e.g.

const int WORLD_HEIGHT = 42;
const int VIEWPOINT_CONSTANT = 8+1;

(Note that the problem goes away with the above declarations and parentheses are no longer required.)

Lessons we have learned today:

  • always use parentheses in #defines (or better yet use const, since this is 2013, not 1983)
  • always post real code on StackOverflow !

Upvotes: 4

Related Questions