C++ 범위, 공간 - 범위

진경천·2023년 9월 15일
0

C++

목록 보기
33/90

유효 범위 scope

유효 범위란 하나의 변환 단위 내에서 해당 변수가 사용될 수 있는 범위를 나타낸다.
함수 내에서 선언된 변수는 함수 내에서만 사용할 수 있고, 함수 밖에서 선언된 변수는 변수가 선언된 이후에 나오는 모든 함수에서 사용할 수 있다.

블록 scope

#include <iostream>

using namespace std;

extern int x = 10;
// 전역적으로 선언하며 외부 소스파일에서도 사용 가능

int Get() {
	return x;
}

int main() {
	int a = 0;
	cout << a << endl;
	cout << &a << endl;
	cout << endl;
	{
		int a = 10;
		cout << a << endl;
		cout << &a << endl;
		cout << endl;
	}
	// scope 내에서만 a가 작용하고 주소 또한 다르다
	cout << a << endl;
	cout << &a << endl;
	cout << endl;

	cout << Get() << endl;

	return 0;
}
  • 코드 실행 결과

    0
    000000D9C3AFFB84

    10
    000000D9C3AFFBA4

    0
    000000D9C3AFFB84

    10

    블록 밖의 a와 블록 안의 a의 값과 주소값 또한 다른걸 알 수 있다.

namespace와 열거형 scope

naemsapce는 같은 변수를

#include <iostream>

using namespace std;

namespace CompanyB {
	int num = 20;
}

namespace CompanyA {
	int num = 10;
}

enum struct RequestType {
	Login, Register, Update, Delete
};
// 열거형 scope

int main() {
	cout << CompanyA::num << endl;
	cout << CompanyB::num << endl;
	
	return 0;
}
  • 코드 실행 결과

    10
    20

    namespace 안의 num이 서로 다른 것을 알 수 있다.

profile
어중이떠중이

0개의 댓글

관련 채용 정보