What is the function of these operators ( =& , ~ ), i found this code posted as a joke and titled
"Found in early Unix sources:"
if(rp->p_flag & SSW开发者_StackOverflow中文版AP) {
rp->p_flag =& ~SSWAP;
aretu(u.u_ssav);
}
EDIT: Source: http://www.bsdlover.cn/study/UnixTree/V6/usr/sys/ken/slp.c.html
~
is unary bitwise complement, which flips the bits in an integer.
However, after reading a comment and realizing I read your code wrong, I realized that the code that you have presented won't even compile in a modern compiler.
Thanks to @Avi: the operator =&
means what &=
means today, but this syntax really predates current C standards so it is truly ancient UNIX code.
What is would really mean today
The &
here should act as the address-of
operator, and not the bitwise AND
operator.
int main()
{
int x = 5;
int y = 2;
x =& ~y;
}
Compiling this code would produce:
error: lvalue required as unary ‘&’ operand
I really think there was a problem in transcription, as logically, it should be &=
and not the other way.
In the case that it is actually &=
, then it is doing a bitwise and.
In early C, the assignment operators had the operator on the right. So it was =&
instead of &=
, and =+
instead of +=
.
So this code just checks if a certain bit is set, and if so, takes action and turns off the bit.
You young whippersnappers were born too late :)
This code comes from a very early version of Unix (pre V7). The joke is that the comment just above it is "You are not supposed to understand this", which has become a bit of a legend.
=&
is actually two separate operators: =
and &
, so the line is equivalent to rp->p_flag = & ~SSWAP;
.
~
is the bitwise NOT operator, so ~SSWAP
will be result of flipping the bits of SSWAP
. & ~SSWAP
will result in the reference of the result of ~SSWAP
, which is a compile error. So the thing won't compile using a modern compiler (since C89), but =&
is equivalent to &=
on modern compilers.
&=
applies the bitwise AND on rp->p_flag
and ~SSWAP
and places the result in rp->p_flag
. The end result is that all 0
bits in SSWAP
will turn off the respective bits in rp->p_flag
if they are set. This will only be executed if at least one 1
bit will be turned off, so as to only call aretu(u.u_ssav)
if the value of rp->p_flag
will change as a result of the operation.
From the horse's mouth:
B introduced generalized assignment operators, using x=+y to add y to x. The notation came from Algol 68 [Wijngaarden 75] via McIlroy, who had incorporated it into his version of TMG. (In B and early C, the operator was spelled =+ instead of += ; this mistake, repaired in 1976, was induced by a seductively easy way of handling the first form in B's lexical analyzer.)
精彩评论