본문 바로가기
공부/TIL

[TIL]2022/03/05

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

매크로

 

매크로 쓸 때는 return 안쓴다.

예를 들어서 두 수를 비교해서 앞에 게 더 크면 1을 반환하고 아니면 0을 반환하는 삼항 연산을 매크로로 구현하고 싶다고 하자.

#define Check(x,y) x > y ? 1 : 0

이렇게 쓰는 게 맞다. 

매크로는 어떤 값을 반환하는 함수를 만드는 게 아니다. 그냥 계산하는 매크로를 만드는 거다.

#define Check(x,y) return (x > y ? 1 : 0)

그래서 이거 처럼 return 문을 넣으면 '식이 필요합니다'라는 오류가 뜬다.

 

삼항 연산자

 

삼항 연산자를 써서 return 값을 받고 싶을 때는 

int check(int x, int y){
	x > y ? return 1 : return 0;
}

 

이렇게 return을 값 마다 앞에 쓰는 게 아니라

int check(int x, int y){
	return x > y ? 1 : 0;
}

이렇게 하는 거다.

 

삼항 연산을 해서 1 또는 0 둘 중 하나를 고르게 되고, 그 다음에 return 하는 것임.

return은 선언문이기 때문에 표현식(expression)안에 사용할 수 없음. 

 

삼항연산자

https://stackoverflow.com/questions/3566413/ternary-operators-and-return-in-c

 

Ternary operators and Return in C

Why can't we use return keyword inside ternary operators in C, like this: sum > 0 ? return 1 : return 0;

stackoverflow.com

expression과 statement

https://farside.ph.utexas.edu/teaching/329/lectures/node11.html

 

Expressions and statements

Next: Operators Up: Scientific programming in C Previous: Variables An expression represents a single data item--usually a number. The expression may consist of a single entity, such as a constant or variable, or it may consist of some combination of such

farside.ph.utexas.edu

 

'공부 > TIL' 카테고리의 다른 글

[TIL]2022/03/09  (0) 2022.03.09
[TIL]2022/03/08  (0) 2022.03.08
[TIL]2022/03/01  (0) 2022.03.01
[TIL]2022/02/22  (0) 2022.02.22
[TIL]2022/02/14  (0) 2022.02.14