728x90
반응형

논리연산자

더보기
# include <stdio.h>
# include <ctype.h>  // islower()
# include <stdbool.h>
# include <iso646.h> // and, or, not

#define PREIOD '.'  

int main(){
	
	/*
		논리 연산자
		&& : and - 조건 둘다 충족해야 맞다
		|| : or - 조건 둘 중에서 하나만 충족해도 맞다.
		! : not - 조건이 참이면 거짓, 거짓이면 참 
	*/
	
	bool test1 = 3 > 2 || 5 > 6; // true 3은 2보다 크기때문에 true 앞에것이 true면 뒤에것을 확인 안한다. || or 연산 자 
	bool test2 = 3 > 2 && 5 > 6; // false 3은 2보다 크지만 5가 6보다 크지는 않으니 false 둘다 참이여야 참
	bool test3 =  !(5>6); // true 5 > 6은 false지만 !은 부정이기 때문에 false를 부정해서 true \
	
	printf("%d\n%d\n%d",test1,test2,test3);
	
}  

[그림1] 논리 연산자 예제 출력

논리 연산자 활용

더보기
# include <stdio.h>
# include <ctype.h>  // islower()
# include <stdbool.h>
# include <iso646.h> // and, or, not

#define PREIOD '.'  

int main(){
	
	// 입력값이 . 면 끝나고 줄바꿈, 공백은 빼고 글자 수 계산 
	char ch;
	int count = 0;
	
	while((ch = getchar())!= PREIOD)
	{
		if(ch !='\n'&& ch !=' ')
			count++;
	}
	printf("%d",count);
}  

[그림2] 논리 연산자 활용 예제 출력

논리 연산자는 !(not)을 제외하고 우선순위가 매우 낮은 편이다.

 

논리 연산자 실행 순서

더보기
# include <stdio.h>
# include <ctype.h>  // islower()
# include <stdbool.h>
# include <iso646.h> // and, or, not

#define PREIOD '.'  

int main(){
	
	int temp = (1+2) * (3+4); // 1+2가 먼저 계산일지. 3+4가 먼저 계산이 될지는 모른다. 
	
	printf("Befor : %d\n", temp);
	
	if(temp == 0 && (++temp == 1024)) // 논리연산자는 왼쪽부터 시작해서 오른쪽으로 이동한다. 
	{
		 
	}; 
	
	printf("After : %d\n", temp);
	//둘다 21이 나온 이유는 밑의 temp 논리 연산자의 경우 왼쪽부터 시작이므로 앞의 temp == 0이 false여서 뒤에 논리연산자는 그냥 생략해버린다.
	 
}  

[그림3] 논리 연산자 실행 순서 예제 출력

 

728x90
반응형
  • 네이버 블러그 공유하기
  • 네이버 밴드에 공유하기
  • 페이스북 공유하기
  • 카카오스토리 공유하기