i.e. -
int result;
result = 125/100;
or
result = 43/100;
Will result always be the floor of the division? What is the defined bahavior?
If you could point me in the right direction, i would appreciate it.
Thank You.
i.e. -
int result;
result = 125/100;
or
result = 43/100;
Will result always be the floor of the division? What is the defined bahavior?
If you could point me in the right direction, i would appreciate it.
Thank You.
Yes, the result is always floor of the division for positive integers. It will round towards smallest absolute value.
-5 / 2 = -2
5 / 2 = 2
Will result always be the floor of the division? What is the defined bahavior?
Yes, integer quotient of the two operands.
6.5.5 Multiplicative operators
6 When integers are divided, the result of the / operator is the algebraic quotient with any fractional part discarded.88) If the quotient a/b is representable, the expression (a/b)*b + a%b shall equal a.
and the corresponding footnote:
88) This is often called ‘‘truncation toward zero’’.
Of course two points to note are:
3 The usual arithmetic conversions are performed on the operands.
and:
5 The result of the / operator is the quotient from the division of the first operand by the second; the result of the % operator is the remainder. In both operations, if the value of the second operand is zero, the behavior is undefined.
[Note: Emphasis mine]
Where the result is negative, C truncates towards 0 rather than flooring - I learnt this reading about why Python integer division always floors here: Why Python's Integer Division Floors
Dirkgently gives an excellent description of integer division in C99, but you should also know that in C89 integer division with a negative operand has an implementation-defined direction.
From the ANSI C draft (3.3.5):
If either operand is negative, whether the result of the / operator is the largest integer less than the algebraic quotient or the smallest integer greater than the algebraic quotient is implementation-defined, as is the sign of the result of the % operator. If the quotient a/b is representable, the expression (a/b)*b + a%b shall equal a.
So watch out with negative numbers when you are stuck with a C89 compiler.
It's a fun fact that C99 chose truncation towards zero because that was how FORTRAN did it. See this message on comp.std.c.