Can I be sure that an odd number in C++ should always return floor of the result when divided in such a way that there is a remainder or are there any exceptions to this? I mean:
int x = 5;
x = x/2;
cout<<x; //2
yes. you can be sure of that in c++
ISO/IEC N3485(working draft) says in 5.6.4
The binary / operator yields the quotient, and the binary % operator yields
the remainder from the division of the first expression by the second.
If the second operand of / or % is zero the behavior is undefined.
For integral operands the / operator yields the algebraic quotient with any
fractional part discarded;81 if the quotient a/b is representable in the type
of the result, (a/b)*b + a%b is equal to a; otherwise, the behavior of both
a/b and a%b is undefined.
Yes; division between integers is always integral division in C++:
[C++11 5.6/4]:
The binary/
operator yields the quotient, and the binary%
operator yields the remainder from the division of the first expression by the second. If the second operand of/
or%
is zero the behavior is undefined. For integral operands the/
operator yields the algebraic quotient with any fractional part discarded; if the quotienta/b
is representable in the type of the result,(a/b)*b + a%b
is equal toa
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With