프로그래밍/C
C/C++ - 쉼표연산자 : Comma Operator
꿈꾸는 사람_Anthony
2022. 3. 11. 16:12
반응형
In the C and C++ programming languages, the comma operator (represented by the token ,) is a binary operator that evaluates its first operand and discards the result, and then evaluates the second operand and returns this value (and type); there is a sequence point between these evaluations.
The use of the comma token as an operator is distinct from its use in function calls and definitions, variable declarations, enum declarations, and similar constructs, where it acts as a separator. - Wikipedia
간단히 예제로 생각해본다.
int a = 1;
int b = 2;
int c = (a += 1,b += 2);
// 앞의 여제에서, comma operator는 first operand에 대하여 계산 수행 후 discard한다.(버린다)
//따라서 a의 값은 2가 된다.(계산은 수행되기 때문)
// second operand에 대해서는 계산 수행 후 해당 값을 반환한다.
//따라서 b의 값은 4가 되고(계산 수행), c의 값도 4가 된다.(secnd operator 반환)
이 방식으로 쉼표를 사용하는 것은, function calls and definitions, variable declarations, enum declarations등의 구문과는 사용이 다르다.
이 때는 분리자로써만 사용된다.
이 또한 예제로 생각해보자.
int func(int a, int b){
return (a,b);
}
int main(){
int a=2, b=3;
func(a, b);
}
위 경우, 쉼표가 연산자로서 사용되는 경우는 return (a,b);
밖에 없다.
나머지의 경우 분리자로써 사용된다.
반응형