hey there i have a simple question to ask.
I have this code with me and the answer of the code is 10.
Could you please explain why?
Code:#include <stdio.h> int main() { int x=!0*10; printf("%d\n", x); return 0; }
hey there i have a simple question to ask.
I have this code with me and the answer of the code is 10.
Could you please explain why?
Code:#include <stdio.h> int main() { int x=!0*10; printf("%d\n", x); return 0; }
! is logical not, not bitwise not, so !0 is 1.
ohhh my bad i understand now thank you
Last edited by YannB; 01-16-2014 at 05:15 PM. Reason: stupid understanding
Before C99, there was not an explicit boolean type in the language. Instead, 0 was used as false and anything non-zero (such as !0) was used as true . Most compilers (if not all) implement that non-zero notion as 1, although I'm not quite sure if the standard guarantees it to be always 1. This behavior still holds in all revisions of the language, although C99 and C11 also support an explicit boolean type (with true/false values).
So what you have there, is treated by your compiler as: x = 1*10
In C, booleans and integers are somewhat conflated. That is, boolean values are really just integer values in a certain context. But due to C's somewhat loose type system, you are allowed to use them interchangeably.
A zero value is false
Any non-zero value is true (e.g. 1, -1, 42, 987654321)
As far as logical (boolean) operators are concerned, it helps to know that
!0 evaluates to 1
!(any non-zero value) evaluates to 0
It also helps keep a C operator precedence chart handy. Notice that the ! has higher precedence than the * (as a multiplication operator, not dereference). Thus it is evaluated first, as though there were imaginary parentheses
Code:!0 * 10 // is equivalent to (!0) * 10 // and NOT !(0 * 10) // this would be !(0) which would be 1