본문 바로가기

Sizeof, 쉼표 연산자, 조건부 연산자 본문

💘 C++/연산자들

Sizeof, 쉼표 연산자, 조건부 연산자

Hyonii 2022. 1. 2. 17:51

Sizeof Operator

어떠한 데이터형의 크기를 알고 싶을 때 사용.

sizeof 연산자는 자료형 또는 변수를 가지고 크기를 byte 단위로 반환하는 연산자다.

특정 시스템에서 자료형의 크기를 결정하기 위해 C++은 sizeof라는 연산자를 제공한다.

 

Opertator Symbol Form Operation
Sizeof sizeof sizeof(type)
sizeof(variable)
Return size of type or variable in bytes

 

C++ 기본 자료형의 크기

Category Type Size Range
boolean bool 1byte true / false
character char 1byte 영숫자 1문자 -128 ~ 127
  unsigned char 1byte 1문자(부호없음) 0 ~255
integer short int 2byte 정수 -32768 ~ 32767
  unsigned short int 2byte 정수(부호없음) 0 ~ 65535
  int 4byte 정수 -2147483648 ~ 2147483647
  unsigned int 4byte 정수(부호없음) 0 ~ 4294967295
  long int 4byte 긴 정수 -2147483648 ~ 2147483647 
  unsigned long int 4byte 긴 정수(부호없음) 0 ~ 4294967295
floating point float 4byte 단정도 부동 소수점 3.4E-38 ~ 3.4E+38
  double 8byte 배정도 부동 소수점 1.7E-308 ~ 1.7E+308
  long double 8byte 확장 배정도 부동 소수점 1.7E-308 ~ 1.7E+308

void 자료형은 크기가 없으므로 sizeof 연산자를 사용할 수 없다.

 

변수 이름을 이용해 sizeof 연산자를 사용할 수 도 있다.

#include <iostream>
using namespace std;

int main()
{
    float a;
    
    cout << sizeof(float) << endl; //4byte = 32bit
    cout << sizeof(a) << endl;
    cout << sizeof a << endl;
    
    return 0;
  }
  
  //sizeof 뒤에는 데이터의 타입, 변수를 넣을 수 있다.
  //sizeof 뒤에 변수명일 경우 괄호가 없어도 작동. 데이터타입은 괄호필요
  //structure나 class 같은 사용자가 만든 자료형에도 sizeof 사용가능
  //메모리 관리할 때 필수적으로 사용
  //sizeof는 함수가 아닌 연산자 operator다.
  
  
  //This produces the result:
  //4
  //4
  //4

쉼표 연산자 Comma Operator

💢헷갈림주의💢

콤마 연산자는 두 개의 표현식을 하나로 결합하는 연산자

문법 규칙상, 하나의 표현식만을 허용하는 자리에 콤마 연산자를 사용하면 두 개의 표현식을 동시에 표현할 수 있다.

 

콤마 연산자는 연산자 중 우선순위가 가장 낮은 연산자이다.

콤마 연산자는 첫 번째 표현식을 먼저 평가한 후, 그 다음 표현식을 평가한다.

 

콤마가 반드시 콤마 연산자로만 사용되는 것은 아니며,

변수 리스트에서 인접한 변수 이름을 분리하는데 쓰이는 콤마는 separator 분리자라고 부른다.

 

#include <iostream>

using namespace std;

int main()
{
    int x = 3;
    int y = 10;
    int z = (++x, ++y);
    
    cout << x << " " << y << " " << z << endl;
    
    return 0;
  }
  
  //This produces the result:
  //4 11 11
  
  //comma로 나열 되어 있을 때 앞에 ++x를 먼저 계산하고
  //그 다음에 뒤에 ++y를 계산하고
  //뒤에 ++y가 z에 들어가게 한다.

얘를 comma operator 안쓰고 풀어서 쓰게 된다면 

#include <iostream>
using namespace std;

int main()
{
    int x = 3;
    int y = 10;
    
    //int z = (++x, ++y); 여기서 comma operator를 안쓰고 풀어서 쓰면
    
    ++x;
    ++y;
    int z = y;
    
    cout << x << " " << y << " " << z << endl;
    
    return 0;
  }
  
  //This produces the result:
  //4 11 11
  //반복문에서 comma operator 많이 사용
#include <iostream>
using namespace std;

int main()
{
    int a =1, b = 10; //여기서 쓴 comma는 단순 구분해주는 기호
    int z;
    
    z = a, b;
    
    cout << z << endl;
    
    return 0;
  }
  
//Thid produces the result:
//1
//comma operator는 우선순위가 등호(대입)연산자보다 낮다
//그래서 대입 먼저함
//(z = a), b; 가 된다
//뒤에 거를 넣어 주고 싶을 때는 괄호 쳐서 z = (a, b);
#include <iostream>
using namespace std;

int main()
{
    int a =1, b = 10; //여기서 쓴 comma는 단순 구분해주는 기호
    int z;
    
    z = (++a, a + b);
    
    cout << z << endl;
    
    return 0;
  }
  
//Thid produces the result:
//12
//a에 1이 더해지고
//z에 10이 더해지면 12가 z에 들어간다.

조건부 연산자 Conditional Operator

Operator Symbol Form Operation
Conditional ? :  c ? x : y If c is nonzero (true) then evaluate x, otherwise evaluate y

조건에 따라서 ~를 해라 라는 의미

조건부 연산자는 항이 3개가 들어가는 유일한 삼항 연산자이다. 

조건을 처리를 할 때 if문을 안쓰고 처리해서 arithmetric if 라고 불리기도 한다

?: 연산자는 if-else 문을 더 간결하게 사용하는 방법을 제공한다.

 

#include <iostream>
using namespace std;

int main()
{
    bool onSale = true;
    
    int price;
    
    if (onSale)
    	price = 10;
    else
    	price = 100;
        
	cout << price << endl;
    
    return 0;
 }
 
//This produces the result:
//10

여기서 int price를 const로 쓰고 싶을 때 조건부 연산자가 유용하게 쓰인다.

#include <iostream>
using namespace std;

int main()
{
    bool onSale = true;
    
    const int price = (onSale == true) ? 10 : 100;
    
    cout << price << endl;
    
    return 0;
    
 }
 
//This produces the result:
//10

//onSale이 true면 price가 10 그렇지 않으면 price가 100
//조건이 true면 콜론 기준 왼쪽에 있는 10이 price에 들어간다.
//조건이 안맞을 때는 콜론 기준 오른쪽에 있는 100이 price에 들어간다.
//if 문을 쓸 때는 price를 const로 딱 씌울 수가 없음.

굳이 if 문을 써야겠다면 함수로 쪼개는 방법이 있다.

#include <iostream>

using namespace std;

int getPrice(bool onSale)
{
	if (onSale)
    		return 10;
   	 else
    		return 100;
 }
 
 int main()
{
    bool onSale = true;
    
    const int price = getPrice(onSale);
    
    cout << price << endl;
    
    return 0;
}

//This produces the result:
//10

이렇게 쓸 수 있다.

간단한 경우에는 conditional operator로 해결하는게 보기도 좋고 깔끔

하지만 복잡한 경우에는 안쓰는게 낫다.

복합한 경우에는 if 문이나 함수로 쪼개서 쓰는게 읽기도 편하고 디버깅 할 때 편함

 

 

일반적인 if - else:

if (condition)
	expression;
else
	other_expression;

를 다음과 같이 작성할 수 있다.

(condition) ? expression : other_expression;

또 다른 예로, 변수 x와 y 중 더 큰 값을 찾기 위해 다음과 같이 작성할 수 있다.

if(x > y)
	larger = x;
else
	larger = y;

를 다음과 같이 작성할 수 있다.

larger = (x > y)? x : y;

?:연산자는 우선순위가 매우 낮다.

우선 순위를 확실하게 하기 위해 조건부분에 괄호 ()를 넣는 게 일반적이다.

#include <iostream>
using namespace std;

int main()
{
    int x = 5;
    
    cout << ((x % 2 == 0) ? "even" : "odd") << endl;
    
    return 0;
}

//This produces the result:
//odd
//연산자 우선순위 때문에 괄호로 쌈

주의 할 점

#include <iostream>
using namespace std;

int main()
{
    int x = 5;
    
    cout << ((x % 2 == 0) ? 0 : "odd") << endl;
    //여기서 0과 "odd"는 타입이 다르니까 이렇게는 사용 안하는게 좋음
    
    return 0;
}

타입이 다를 때는 안쓰는게 좋다.

Comments