Program Tip

C 및 C ++에서 세미콜론 대신 쉼표를 사용하는 경우의 효과

programtip 2020. 11. 30. 19:47
반응형

C 및 C ++에서 세미콜론 대신 쉼표를 사용하는 경우의 효과


여러 C 및 C ++ 코드를 리팩토링 할 때 세미콜론이 아닌 쉼표가 문을 구분하는 데 사용된다는 사실을 여러 차례 발견했습니다. 이 같은;

int a = 0, b = 0;
a = 5, b = 5;

내가 예상했던 곳

int a = 0, b = 0;
a = 5; b = 5;

C와 C ++에서 쉼표를 사용하여 문 (특히 루프 헤더)을 구분할 수 있다는 것을 알고 있지만이 두 코드 사이에 차이점이 있다면 무엇입니까? 내 생각 엔 잘라 내기 및 붙여 넣기의 결과로 쉼표가 남아 있지만 버그이며 실행에 영향을 미칩니 까?


게시 한 코드에는 차이가 없습니다. 일반적으로 쉼표는 세미콜론처럼 표현식을 구분하지만 전체를 표현식으로 취하면 쉼표 연산자는 표현식이 마지막 인수로 평가됨을 의미합니다.

예를 들면 다음과 같습니다.

b = (3, 5);

3, 5를 평가하고 후자를 b에 할당합니다. 그래서 b = 5. 여기서는 대괄호가 중요합니다.

b = 3, 5;

평가합니다 b = 3다음 5 전체 식의 결과는 그럼에도 불구하고, 5 b == 3.

쉼표 연산자는 반복기 코드가 단순하지 i++않지만 여러 명령을 수행해야하는 경우 for 루프에서 특히 유용 합니다. 이 경우 세미콜론은 for 루프 구문에서 잘 작동하지 않습니다.


쉼표는 항상 두 번째 (오른쪽) 인수 인 값을 반환하는 연산자이며 세미콜론은 명령문을 끝냅니다. 이를 통해 쉼표 연산자를 다른 문 내에서 사용하거나 여러 문을 하나로 연결하여 표시 할 수 있습니다.

여기서 함수 f (x)가 호출 된 다음 x > yif 문에 대해 평가됩니다.

if( y = f(x), x > y )

블록의 필요성을 피하기 위해 사용되는 예

if( ... )
   x = 2, y = 3;

if( ... ) {
   x = 2;
   y = 3;
}

쉼표 연산자는 왼쪽에서 오른쪽으로 모든 피연산자를 평가하고 결과는 마지막 피연산자의 값입니다.

예를 들어 (문자열 반전) "증가"부분에서 여러 작업을 수행하려는 경우 for 루프에서 주로 유용합니다.

for (int lower = 0, upper = s.size() - 1; lower < upper; ++lower, --upper)
    std::swap(s[lower], s[upper]);

옵션 일 수있는 또 다른 예 (문자열의 모든 항목 찾기) :

#include <string>
#include <iostream>

int main()
{
    std::string s("abracadabra");
    size_t search_position = 0;
    size_t position = 0;

    while (position = s.find('a', search_position), position != std::string::npos) {
        std::cout << position << '\n';
        search_position = position + 1;
    }
}

에서, 특정 논리 문자가 문자열에 있음을 의미 할 수있다 제로 0이 아닌 모두 있기 때문에,이 조건을 사용할 수 없습니다. 반면에 쉼표를 사용하면 position = s.find()조건이 평가 될 때마다 호출되지만 조건의이 부분의 결과는 무시됩니다.

당연히 루프를 작성하는 다른 방법이 있습니다.

while ((position = s.find('a', search_position)) != std::string::npos)

아니면 그냥

while (true) {
    position = s.find('a', search_position);
    if (position == std::string::npos)
        break;
    ...
}

코드 골프에서 한 가지 사용법이 있습니다.

if (x == 1) y = 2, z = 3;
if (x == 1) { y = 2; z = 3; }

The first line is shorter, but that looks too confusing to use in regular development.


As Frank mentioned, how the comma operator is used in your example doesn't cause a bug. The comma operator can be confusing for several reasons:

  • it's not seen too often because it's only necessary in some special situations
  • there are several other syntactic uses of the comma that may look like a comma operator - but they aren't (the commas used to separate function parameters/arguments, the commas used to separate variable declarations or initializers)

Since it's confusing and often unnecessary, the comma operator should be avoided except for some very specific situations:

  • it can be useful to perform multiple operation in one or more of a for statement's controlling expressions
  • it can be used in preprocessor macros to evaluate more than one expression in a single statement. This is usually done to allow a macros to do more than one thing and still be a a single expression so the macro will 'fit' in places that only allow an expression.

The comma operator is a hackish operator pretty much by definition - it's to hack in 2 things where only one is allowed. It's almost always ugly, but sometimes that's all you've got. And that's the only time you should use it - if you have another option, don't use the comma operator.

Off the top of my head I can't think of too many other reasons to use the operator, since you can get a similar effect by evaluating the expressions in separate statements in most other situations (though I'm sure that someone will comment on a another use that I've overlooked).

참고URL : https://stackoverflow.com/questions/2087026/effect-of-using-a-comma-instead-of-a-semi-colon-in-c-and-c

반응형