how the output is calculated?
I'm confused in this program how the value of x=320 ...
#include<stdio.h>
int a=5;
int main(){
int x;
x=~a+a&a+a<<a;
pr开发者_开发百科intf("%d",x);
return 0;
}
http://codepad.org/UBgkwdYl
hoping for quick and positive response..
This is evaluated like this:
x = ((~a) + a) & ((a + a) << a);
You should review the C operator precedence tables.
Actually, that will only give you 320 if your implementation uses two's complement encoding for integers. The reason why is because it's interpreted as:
(((~a) + a) & ((a + a) << a))
= -1 & (10 << 5)
= 10 << 5
= 320
The -1 in two's complement is all 1-bits so when you and
that with anything, you get the same value.
However, with one's complement, ~a + a
will give you zero so that the final result is zero.
The ISO C standard allows two's complement, one's complement and sign/magnitude encoding for signed integers and this is one reason why such code is inherently bad.
Read this Bits Operators OR this Bits Operators
The code makes use of the following operators (listed in the order shown in the equation):
- ~
- +
- &
- <<
Given the operator precedence table for the C languages, the operators will be evaluated in the following order:
- ~
- +
- <<
- &
Given this, we have the following steps:
- ~5. The bitwise negation of 5 (which, in binary, is 0000101) is 250 (which, in binary, is 11111010).
- ~5 + 5 is 250 + 5, or 255.
- 5 + 5 is 10.
- 10 << 5 is the value of 10 (which, in binary, is 00001010) left shifted five bits, which is 320 (which, in binary, is 101000000).
- 255 (which, in binary, is 11111111) joined in a Boolean AND operation with 320 (which, in binary, is 101000000) gives a value of 320 (which, in binary, is 101000000).
This gives the final value of 320.
精彩评论