본문 바로가기
language/C

연산자 II

by abstract.jiin 2022. 9. 5.
  1. 논리연산자
  2. 증감연산자
  3. 비트연산자

 

 


 

1. 논리연산자 


논리 연산 중 or 연산과 and 연산, not 연산을 의미하는 연산자 


|| : or연산자 (shift+ \)
조건식 1 || 조건식 2
조건식중 하나라도 참이면 결과는 참 
조건식이 전부 거짓이면 결과는 거짓

&& : and 연산자
조건식 중 하나라도 거짓이 있으면 결과는 거짓
조건식이 전부 참이면 결과는 참 

! : not 연산자
!(조건식)
조건식이 참이면 결과는 거짓 
조건식이 거짓이면 결과는 참 

 

int a = 10, b = 20;

//AND 연산
printf("a != 10||b<20:%d\n", a != 10 || b < 20);		//0 (false)
printf("a != 10||b<=20:%d\n", a != 10 || b <= 20);		//1
printf("a == 10||b<20:%d\n", a == 10 || b < 20);		//1
printf("a == 10||b<=20:%d\n", a == 10 || b <= 20);		//1 (true)

//OR 연산
printf("a != 10 && b<20:%d\n", a != 10 && b < 20);		//0 (false)
printf("a != 10 && b<=20:%d\n", a != 10 && b <= 20);	//0
printf("a == 10 && b<20:%d\n", a == 10 && b < 20);		//0
printf("a == 10 && b<=20:%d\n", a == 10 && b <= 20);	//1 (true)
	
//NOT 연산
printf("!(a != 10) :%d\n", !(a != 10));		//1  ->  F가 결과니 T로 도출. 
printf("!(a == 10) :%d\n", !(a == 10));		//0  -> T가 결과니 F 도출

 

 

2. 증감 연산자

 
데이터를 1 증가시키거나 감소 시킬 때 사용 

++ : 1 증가 
-- : 1 감소 


증감 연산자는 전위 연산과 후위 연산으로 분류

++n : 1 증가 후 다른 연산 
n++ : 다른 연산 후 1 증가 
--n : 1 감소 후 다른 연산 
n-- : 다른 연산 후 1 감소

int c = 5, d = 0;

printf("c : %d\n\n", c);					//c:5

d = ++c * 2;
printf("++c *2 >> c : %d, d:%d\n", c, d);	// c:6, d:12

d = c++ * 2;
printf("c++ *2 >> c : %d, d:%d\n", c, d);	// c:7, d:12

d = --c * 2;
printf("--c *2 >> c : %d, d:%d\n", c, d);	// c:6, d:12

d = c-- * 2;
printf("c-- *2 >> c : %d, d:%d\n", c, d);	// c:5, d:12

 

3. 비트 연산자 

 

bit : 2진수 한 자리 
연산 되는 숫자를 2진수로 변경하여 bit 단위로 연산 

| : bit or (shift +\)
& : bit and
^ : bit xor(xor : 두 논리값이 같으면 0, 다르면 1)
~ : bit not(보수 개념까지 사용 + CPU에 따라 연산 차이 발생)
<< : bit shift(left)
>> : bit shift(right)

 

int e = 12;								//1100
int f = 7;								//0111

print("%d | %d = %d\n", e, f, e | f);	//1111 = 15
print("%d & %d = %d\n", e, f, e & f);	//0100 = 4
print("%d ^ %d = %d\n", e, f, e ^ f);	//1011 = 11


int g = 20;								// 10100
printf("~%d = %d\n", g, ~g);			// ??        ~20=-21  보수 때문에 추후 다시
printf("~%d << %d\n", g, g << 2);		// 1010000		= 80
printf("~%d >> %d\n", g, g >> 2);		// 101			= 5

'language > C' 카테고리의 다른 글

조건 제어문  (0) 2022.09.05
입력함수  (0) 2022.09.05
연산자  (0) 2022.09.05
형변환  (0) 2022.09.04
자료형  (0) 2022.09.04