영어로 읽는 코딩

20 [C] 대입(할당) 연산자와 표현식 (복합 대입 연산자)

Assignment Operators and Expressions (대입(할당) 연산자와 표현식)

 

Expressions such as

 

i = i + 2

 

in which the variable on the left hand side is repeated immediately on the right, can be written in the compressed form

 

i += 2

 

The operator += is called an assignment operator.

 

Most binary operators (operators like + that have a left and right operand) have a corresponding assignment operator op=, where op is one of

 

+      -      *     /      %      <<      >>      &

 

If expr 1 and expr 2 are expressions, then

 

expr 1 op = expr 2

 

is equivalent to

 

expr1 = (expr1) op (expr2)

 

except that expr1 is computed only once. Notice the parentheses around expr2:

 

x *= y + 1

 

means

 

x = x * (y + 1)

 

rather than

 

x = x * y + 1

 

As an example, the function bitcount counts the number of 1-bits in its integer argument.

  


#include <stdio.h>

/* count 1 bites in x */

int bitcount(unsigned int);

int main(void)

{

    unsigned int src = 14;

    printf("%d \n %s", bitcount(src), "t");

    return 0;

}

 bitcount(unsigned int x) {

    int b;

/*  for (b = 0; x != 0; x >>= 1){

           if (x & 01) {

                 b++;

           }            

    }

*/

    for (b = 0; x != 0; x &= (x-1)) {

                 b++;

    }

    return  b;

} [원본에서 출력 프로그램 만들었음]

 

 

Declaring the argument x to be unsigned ensures that when it is right-shifted, vacated bits will be filled with zeros, not sign bits, regardless of the machine the program is run on.

 

 

 

[The C Programming Language p.50]

댓글

댓글 본문
버전 관리
Yoo Moon Il
현재 버전
선택 버전
graphittie 자세히 보기