mathcom
mathcom

Reputation: 113

What is the difference of this code?

#include <stdio.h>

int main(void)
{        
  double aRate[10] = { 0.0, 0.1, 0.25, 0.5, 0.5, 0.6, 0.65, 0.8, 0.82, 0.97};
  int nAge = 0, i = 0, nFee = 1000;
  int a = 0;

  printf("%d  : \t%d \n", i, (int)(nFee*aRate[2]));
  return 0;
}

The result of this code is 0 : 250, as expected, but if I omit the parentheses like this,

printf("%d  : \t%d \n", i, (int)nFee*aRate[2]);

then the result is 0 : 0.

Why are

printf("%d  : \t%d \n", i, (int)(nFee*aRate[2]));

and

printf("%d  : \t%d \n", i, (int)nFee*aRate[2]);

different?

Is it related to order of priority?

Upvotes: 2

Views: 83

Answers (2)

John Messenger
John Messenger

Reputation: 351

Yes, it's related to the parentheses. The (int) binds very tightly, so in the second example it casts nFee to integer, which is a bit pointless as it's already an integer. The * then multiplies int and double, producing double. In the first example, the parenthesised expression (nFee*aRate[2]), which is of type double, is cast to integer by the (int).

Here's a table of the operator precedences.

Upvotes: 1

Jabberwocky
Jabberwocky

Reputation: 50778

The type of (int)nFee*aRate[2] is double, because it's the same as ((int)nFee)*aRate[2] because of operator precedence and the result of a multiplication of a double and an int is promoted to double. Therefore you are using %d as format specifier for a double which yields in undefined behaviour.

The type of (int)(nFee*aRate[2]) is int therefore %d as format specifier is correct and you get the exepected result of 250 (0.25 * 1000).

Upvotes: 8

Related Questions