-3
int i = 2, j = 3, k, l ;
float a, b ;
k = i / j * j ;
l = j / i * i ;
a = i / j * j ;
b = j / i * i ;
printf( "%d %d %f %f", k, l, a, b ) ;
}

it is a simple c program from yashwant kanetkar but i could not relate to the answer . if we compile this program the output which i am getting is

0 2 0.00000 2.00000

this is a very simple program but i am not able to explain the output may be i am getting confused with the associativity. both / and * have L to R associativity and only / has unambiguous left operand (necessary condition for L to R associativity) it is performed earlier. but the answer is different in that case .

  • 2
    First kick out that rubbish book out of your desk and then pick some good book/tutorial. – haccks Jun 29 '15 at 14:57
  • The associativity or precedence is as you expected, the thing you are confused is **integer division**. – Yu Hao Jun 29 '15 at 15:00

1 Answers1

1

It is simple associativity of the operators, nothing complex.

I think it's the "integer division" property which is making you confused.

  1. k = i / j * j ; answer 0, because of integer division first (i / j == 0).
  2. l = j / i * i ; answer 2, because of integer division first. (j / i == 1)
  3. a = i / j * j ; answer 0, (promoted to float) because of integer division first, as I mentioned earlier.
  4. b = j / i * i ;, answer 2, (promoted to float) because of integer division first, alo mentioned earlier.

Note: A gentle version of what Mr. Haccks said : Please avoid referring that particular book.

Community
  • 1
  • 1
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261