0

I have a question about C behavior I don't understand...

#define KB 1024
#define FOUR_KB 4*KB

int main() {
  uint32_t a;
  uint32_t b = 24576;

  a = ceil((float)b/FOUR_KB);
  //want to get number of 4K transfers 
  //(and possibly last transfer that is less than than 4K)
}

At this point I would expect a to be 6, but result I get is 96.

Any explanation for this?

Rorschach
  • 734
  • 2
  • 7
  • 22
  • 1
    Check the macro expansion. Use parenthesis. – Sourav Ghosh Mar 28 '19 at 13:10
  • 4
    Please calculate for me `24576/4*1024` ? It's a) `6291456` or b) `6`? – KamilCuk Mar 28 '19 at 13:11
  • 2
    Macros are just a textual replacement, so `a = ceil((float)b/FOUR_KB);` expands to `a = ceil((float)b/4*1024);`. To fix it, use parentheses in the macro expansion like so: `#define FOUR_KB (4*KB)` so that you end up with `a = ceil((float)b/(4*1024));`. – Ian Abbott Mar 28 '19 at 13:12

1 Answers1

4

Multiplication and division have the same priority but compiler compute from left to right when push to stack :

24576÷(4×1024) = 6         // what you expect
24576÷4×1024 = 6291456     // what compiler compute, this mean : 6144 * 1024

You should use of parenthesis and #define like this :

#define FOUR_KB (4*KB)