기타 연산자
sizeof 연산자
sizeof
연산자는 데이터 타입이나 표현식의 크기를 바이트 단위로 반환합니다.
기본 사용법
#include <iostream>
int main() {
std::cout << "Size of int: " << sizeof(int) << " bytes\n";
std::cout << "Size of char: " << sizeof(char) << " byte\n";
std::cout << "Size of float: " << sizeof(float) << " bytes\n";
std::cout << "Size of double: " << sizeof(double) << " bytes\n";
int arr[10];
std::cout << "Size of int array with 10 elements: " << sizeof(arr) << " bytes\n";
return 0;
}
sizeof와 포인터
#include <iostream>
int main() {
int* ptr = nullptr;
std::cout << "Size of int pointer: " << sizeof(ptr) << " bytes\n";
std::cout << "Size of int pointed to: " << sizeof(*ptr) << " bytes\n";
char* char_ptr = nullptr;
std::cout << "Size of char pointer: " << sizeof(char_ptr) << " bytes\n";
std::cout << "Size of char pointed to: " << sizeof(*char_ptr) << " byte\n";
return 0;
}
sizeof와 구조체
#include <iostream>
struct Example {
char c;
int i;
double d;
};
int main() {
std::cout << "Size of Example struct: " << sizeof(Example) << " bytes\n";
std::cout << "Sum of member sizes: "
<< sizeof(char) + sizeof(int) + sizeof(double) << " bytes\n";
return 0;
}
주의 : 구조체의 크기는 멤버들의 크기 합과 다를 수 있습니다. 이는 메모리 정렬(alignment) 때문입니다.
sizeof의 주의사항
sizeof
는 컴파일 시간에 평가되므로, 동적으로 할당된 메모리의 크기는 알 수 없습니다.- 배열이 함수 인자로 전달될 때,
sizeof
는 포인터의 크기를 반환합니다.
#include <iostream>
void printArraySize(int arr[]) {
std::cout << "Size of arr in function: " << sizeof(arr) << " bytes\n";
}
int main() {
int arr[10];
std::cout << "Size of arr in main: " << sizeof(arr) << " bytes\n";
printArraySize(arr);
return 0;
}
조건 연산자 ?:
조건 연산자 ?:
는 C++에서 유일한 삼항 연산자입니다.
기본 문법
condition ? expression1 : expression2
condition이 true
면 expression1이, false
면 expression2가 평가됩니다.
사용 예시
#include <iostream>
int main() {
int a = 10, b = 20;
int max = (a > b) ? a : b;
std::cout << "Maximum of " << a << " and " << b << " is: " << max << std::endl;
std::string result = (a % 2 == 0) ? "even" : "odd";
std::cout << a << " is " << result << std::endl;
return 0;
}
중첩 사용
조건 연산자는 중첩해서 사용할 수 있지만, 가독성이 떨어질 수 있습니다.
#include <iostream>
int main() {
int a = 10, b = 20, c = 15;
int max = (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c);
std::cout << "Maximum of " << a << ", " << b << ", and " << c << " is: " << max << std::endl;
return 0;
}
주의사항
- 과도한 사용은 코드의 가독성을 해칠 수 있습니다.
- 복잡한 조건은 if-else 문을 사용하는 것이 좋습니다.
콤마 연산자 ,
콤마 연산자는 여러 표현식을 하나의 표현식으로 결합합니다.
기본 사용법
#include <iostream>
int main() {
int a = 1, b = 2, c = 3; // 변수 선언에서의 콤마
int x = (a++, b++, c++); // 콤마 연산자
std::cout << "x: " << x << ", a: " << a << ", b: " << b << ", c: " << c << std::endl;
return 0;
}
for 루프에서의 사용
#include <iostream>
int main() {
for (int i = 0, j = 10; i < 5; i++, j--) {
std::cout << "i: " << i << ", j: " << j << std::endl;
}
return 0;
}
주의사항
- 연산자 우선순위가 가장 낮습니다.
- 과도한 사용은 코드의 가독성을 해칠 수 있습니다.
typeid 연산자
typeid
연산자는 객체의 타입 정보를 반환합니다.
#include <iostream>
#include <typeinfo>
class Base { virtual void dummy() {} };
class Derived : public Base { };
int main() {
int i = 5;
double d = 3.14;
Base* b = new Derived();
std::cout << "Type of i: " << typeid(i).name() << std::endl;
std::cout << "Type of d: " << typeid(d).name() << std::endl;
std::cout << "Type of *b: " << typeid(*b).name() << std::endl;
delete b;
return 0;
}
주의 : typeid
의 결과는 컴파일러에 따라 다를 수 있습니다.
연습 문제
- 다양한 데이터 타입
int
,char
,float
,double
,long long
의 크기를 출력하는 프로그램을 작성하세요. - 조건 연산자를 사용하여 세 수 중 최대값을 찾는 프로그램을 작성하세요.
- 콤마 연산자를 사용하여 1부터 10까지의 숫자 중 짝수만 출력하는 for 루프를 작성하세요.
typeid
연산자를 사용하여 사용자 정의 클래스의 타입 정보를 출력하는 프로그램을 작성하세요.sizeof
연산자를 사용하여 구조체의 크기와 그 멤버들의 크기 합의 차이를 계산하는 프로그램을 작성하세요.
참고자료
- C++ 표준 문서의 표현식 섹션 : Expressions
sizeof
연산자의 세부 사항 : sizeof operatortypeid
연산자와 RTTI : Run-time type information- 조건 연산자 : Conditional operator
- 콤마 연산자 : Comma operator