C++/기타

[C++] Statement vs Expression

sseram 2023. 6. 25. 12:14
반응형

제대로 몰라도 구현할 때엔 큰 차이가 없는 것이지만, 그래도 정확히 알아두면 좋겠다 싶어서 정리.

 

 

C++ 공식 문서에서 basic concepts를 들어가 보면 아래와 같이 statement/ expressions에 대한 간단한 설명을 볼 수 있다.

 

저렇게 되어 있는 걸 보니 일단 두 가지는 확실하게 알겠다.

기본 컨셉에 나올 만큼 C++의 근본 요소라는 것.

statement가 expression보다 상위 표현이라는 것.

 


1. Statement

 

https://en.cppreference.com/w/cpp/language/statements

 

Statements - cppreference.com

Statements are fragments of the C++ program that are executed in sequence. The body of any function is a sequence of statements. For example: int main() { int n = 1; // declaration statement n = n + 1; // expression statement std::cout << "n = " << n << '\

en.cppreference.com

Statements are fragments of the C++ program that are executed in sequence. The body of any function is a sequence of statements.

 

C++로 구현된 프로그램의 기본적인 동작 단위이다.

 

 

종류는 아래와 같다.

C++ includes the following types of statements:

1) labeled statements;
2) expression statements;
3) compound statements;
4) selection statements;
5) iteration statements;
6) jump statements;
7) declaration statements;
8) try blocks;
9) atomic and synchronized blocks (TM TS).

 

 

 

각각 statement들을 살펴보기 전, statement 자체의 특징을 몇 가지 보자면 

 

  • 문장 형태로 되어 있다. (보통 ; 로 끝남.)
  • 기본적으론 위에서 아래, 순차적으로 수행된다.
  • 일련의 동작을 수행한 뒤 프로그램의 상태를 변경할 수 있다.
  • 흐름을 변경 할 수 있는 조건문, 반복문 등을 가지고 있다.

 

 

예시 코드를 통해 보자면

int main()
{
    int n = 1;                        // declaration statement
    n = n + 1;                        // expression statement
    
    if (n == 2){				   	  // Selection statements
    	std::cout << n << endl;
        
        {                                /* compound statement start
            std::cout << n + 1 << endl;  /   
            std::cout << n 2 1 << endl;  /
        }                                */  compound statement end
    
    } else {
        while(n != 2){                // Iteration statements
            n = n + 1;
            
            if (n < 0){
                break;                // Jump Statement
            }
        }
    }
    
    try{                              //Try Blocks
       n = n / 0;
    } catch (...){
       std::cout  << "error" << std::endl;
    }
    
    switch (n){
        case 1:                       // label statements
        default:
    }
    
    return 0;                         // return statement
}

 

이런 식으로, 우리가 그동안 [~~~ ; ] 이런 식으로 코드를 짰던 모든 것들이 statement이다.

 

 

위 코드에서 안 나온 statement 중 atomic and synchronized blocks 는, 동기화 관련 statement인 듯 한데... 아직 제대로 나오진 않은 듯 하니 기다려 보자.

 


2. Expressions

 

https://en.cppreference.com/w/cpp/language/expressions

 

Expressions - cppreference.com

An expression is a sequence of operators and their operands, that specifies a computation. Expression evaluation may produce a result (e.g., evaluation of 2 + 2 produces the result 4) and may generate side-effects (e.g. evaluation of std::printf("%d", 4) p

en.cppreference.com

An expression is a sequence of operators and their operands, that specifies a computation.

 

operator와 operand들을 가지고, 계산 결과를 돌려주는 것을 expression 이라고 보면 된다.

 

종류는 너무 많다. 어떠한 동작을 하고, 그 동작의 결과로 값을 반환시켜 주는 모든 것들이 expressions이다. 위에 있는 링크에 들어가서 스크롤 한번만 적당히 내려 보자. 익숙한 많은 식들이 보일 것이다.

 

 

expressions들의 특징은

 

  • 변수, 상수, 연산자, 함수 호출 등오로 구성되어 계산 가능한 형태를 가지고, 값으로 평가된다.
  • 항상 즉정한 자료형을 가진다. 이 자료형은 피연산자의 자료형 / 연산자에 의해 결정된다.
  • 중첩이 가능하며, 복잡한 계산식으로 구성할 수 있다.
  • 값을 계산하는 과정에서 프로그램의 상태를 변화시키지 않고, 계산에 필요한 행동만을 수행한다.

 

 

예시로 몇 개만 가져와 보면

 

int a = 5;
int b = 3;

int c = a + b * 2;
// 산술 연산자 + 와 * 연산자를 이용하여 세개의 값을 계산하는 expressions

bool result = (a > b) && (c < 10);
// 산술 연산자 / 논리 연산자를 동시에 이용하여 결과를 뽑아내는 expressions


int square = pow(a, 2);
double sqrt_value = sqrt(square);
// 함수를 이용한 expressions

auto cmp = [](auto a, auto b) -> bool {return a< b;};
bool cmpres = cmp(1,2);
// lambda를 이용한 expressions

...

 

등등.

 

값을 얻기 위해, operators를 활용하여 만드는 모든 것들이 expressions이다.

 


 

 

둘 다 C++ 의 코드의 기본이 되는 개념들이다. 우리가 열심히 코드를 짜는 것을 자세히 들여다보면, expression을 통하여 어딘가에서 값을 가져오고, statement를 이용하여 다음에 어떤 동작을 할 지 지정해주거나, 흐름을 제어하거나 하는 행동의 반복이다.

 

statement 는 프로그램의 흐름 제어/ 동작 수행.

expression은 값을 계산 / 반환.

 

 

이 두 가지만 완벽하게 알고 있다면 되지 않을까?

 

 

 

 

 

 

* 잘못된 정보는 알려주시면 감사한 마음으로 수정하겠습니다.

반응형

'C++ > 기타' 카테고리의 다른 글

[C++ 20] requires  (0) 2024.02.22
[C++] CRTP 패턴.  (1) 2024.02.13
[C++] 함수에 const 한정자  (0) 2023.06.15
[C++] type cast (static_cast, dynamic_cast, const_cast, reinterpret_cast)  (0) 2023.05.18
[C++17] if constexpr  (1) 2023.05.17