Why is this code giving -2 instead of 7?
#include <stdio.h>
main()
{
printf("%i\n", 105 % 3*4 - 3*4 % (101 / 10));
system("pause");
}
Why is this code giving -2 instead of 7?
#include <stdio.h>
main()
{
printf("%i\n", 105 % 3*4 - 3*4 % (101 / 10));
system("pause");
}
I did so and gave 7:
#include <stdio.h>
int main() {
printf("%i\n", 105 % (3 * 4) - (3 * 4) % (101 / 10));
return 0;
}
See working on ideone .
You've probably interpreted the expression without considering precedence and associativity of operators . The rest operator has the same precedence of multiplication and associativity by the left, so in an expression with the two operators what appears first will be executed. To increase the precedence of an operator, you must use the high-priority parent operator.
The second pair of parentheses is not necessary, I put it just to help better see the separation. The last pair, which already existed, solves the problem of precedence that could exist.