안녕하십니까. 김동우입니다.
이번 노트는 다양한 연산자들에 대한 내용입니다.
바로 코드부터 보도록 하겠습니다.
#include <iostream>
int getPrice(bool onSale)
{
if(onSale)
return 10;
else
return 100;
}
int main()
{
using namespace std;
float a(1.44f);
cout << sizeof(float) << endl; // output : 4
cout << sizeof(a) << '\n' << endl; // output : 4
// sizeof는 operator로 분류된다.
// float의 경우 4byte 자료형
int x(3);
int y(10);
int z((++x, ++y));
// ++x; ++y; int z = y; 와 comma operator 결과가 동일한 값이 된다.
cout << x << " " << y << " " << z << '\n' << endl;
// output : 4 11 11
int b = 1, c = 10;
int d;
d = (b++, b + c++); // 2. 이에 괄호를 입력해준다.
// 1. associativity에 의해 comma 보다 assignment가 우선적으로 처리된다.
cout << d << endl; // output : 12
cout << d << '\n' << endl;
bool onSale = true;
int price;
// if
if(onSale)
price = 10;
else
price = 100;
// conditional operator (arithmetric if)
const int cPrice = (onSale == true) ? 10 : 100;
// 이처럼 삼항연산자, 조건부연산자의 경우 const 값임에도
// 조건문으로 활용할 수 있다.
cout << price << " " << cPrice << '\n' << endl; // output : 10 10
const int fPrice = getPrice(onSale);
cout << fPrice << endl; // output : 10
// 다른 방법으로 const 값을 조건문에서 사용하려면, 함수를 만드는 방법도 있다.
// 조건이나 변수가 복잡한 경우는 if 문으로 쪼개어 작성하는 것이 코드가 아름답다.
int i(5);
cout << ((i % 2 == 0) ? "even" : "odd") << endl;
// associativity에 의해 괄호를 작성해야 한다.
// 삼항연산자의 경우 동일한 타입의 값을 출력하는 것을 권장한다.
// 백준 고양이 문제의 해결은 역시 괄호였는가? 생각해보자.
return 0;
}
그럼 이번 글은 이만 마치도록 하겠습니다. 감사합니다.