본문 바로가기
카테고리 없음

[TIL]2022/03/06

by 노르웨이모리 2022. 3. 6.

C 연산자 우선순위

 

다음과 같은 코드가 있다고 하자. check()함수의 결과를 c에 저장하고 max와 비교해서 max보다 크면 c값을 새로운 max로 지정하고자 한다.

if (c = check(arr1, arr2, num) > max) max = c;

코드 한 줄에 하는 일이 많아 보이는데, 실행되는 순서를 잘 보면 의도한 바와 다른 결과가 나오는 것을 알 수 있다.

 

우선, 이 줄이 실행되면 if() 안의 조건이 실행된다. check()함수가 실행되고 결과 값이 c에 저장된다 -> 아니다!!

왜냐하면 연산자 우선순위는 '>'가 '='보다 우선시되기 때문에, check 결과값 > max 의 값(true, false의 bool 값)이 c에 저장된다.

그렇기 때문에 c값은 1 또는 0 둘 중 하나를 가지게 된다. 

원래 의도한 대로 코드가 동작하게 만드려면 우선순위가 후순위인 '=' 연산을 먼저 하기 위해 (c = check(arr1,arr2,num))로 묶어줘야 한다.

 

if ((c = check(arr1, arr2, num)) > max) max = c;

 

코드가 원하는 대로 동작하게 만들기 위해서는 연산자 우선순위를 잘 알아보도록 하자.

 

 

       
1 ++ -- Suffix/postfix increment and decrement Left-to-right
() Function call
[] Array subscripting
. Structure and union member access
-> Structure and union member access through pointer
(type){list} Compound literal(C99)
2 ++ -- Prefix increment and decrement Right-to-left
+ - Unary plus and minus
! ~ Logical NOT and bitwise NOT
(type) Cast
* Indirection (dereference)
& Address-of
sizeof Size-of
_Alignof Alignment requirement(C11)
3 * / % Multiplication, division, and remainder Left-to-right
4 + - Addition and subtraction
5 << >> Bitwise left shift and right shift
6 < <= For relational operators < and ≤ respectively
> >= For relational operators > and ≥ respectively
7 == != For relational = and ≠ respectively
8 & Bitwise AND
9 ^ Bitwise XOR (exclusive or)
10 | Bitwise OR (inclusive or)
11 && Logical AND
12 || Logical OR
13 ?: Ternary conditional Right-to-left
14 = Simple assignment
+= -= Assignment by sum and difference
*= /= %= Assignment by product, quotient, and remainder
<<= >>= Assignment by bitwise left shift and right shift
&= ^= |= Assignment by bitwise AND, XOR, and OR
15 , Comma Left-to-right

 

추가로 if(조건), for(조건) 등 조건 부분에 변수를 정의하면, 그 변수의 scope는 해당 if문, for문 안에서만 유효하다.

예를 들어서 다음과 같은 코드가 있다고 하자.

if ((int c = check(arr1, arr2, num)) > max) max = c;
printf("%d", c);

이러면 오류가 난다. c 변수가 if문 안에서 선언되었으므로 그 밖에서는 선언되지 않은 걸로 인식되기 때문이다.