6.5 Variable shadowing (name hiding)

주홍영·2022년 3월 12일
0

Learncpp.com

목록 보기
64/199

https://www.learncpp.com/cpp-tutorial/variable-shadowing-name-hiding/

각 블록은 고유한 영역을 가지게 된다
만약 nested된 블록 안에서 밖에서 이미 정의된 identifier의 이름을
사용하면 어떻게 될까?
이러한 경우 블록 밖의 원래 identifier를 숨기고 nested block에서 정의된
의미로 사용하게 된다
이를 name hiding or shadowing이라고 불린다.

Shadowing of local variables

#include <iostream>

int main()
{ // outer block
    int apples { 5 }; // here's the outer block apples

    { // nested block
        // apples refers to outer block apples here
        std::cout << apples << '\n'; // print value of outer block apples

        int apples{ 0 }; // define apples in the scope of the nested block

        // apples now refers to the nested block apples
        // the outer block apples is temporarily hidden

        apples = 10; // this assigns value 10 to nested block apples, not outer block apples

        std::cout << apples << '\n'; // print value of nested block apples
    } // nested block apples destroyed


    std::cout << apples << '\n'; // prints value of outer block apples

    return 0;
} // outer block apples destroyed

위의 코드는 다음과 같은 출력을 낸다

5
10
5

따라서 nested block안에서 새롭게 정의한 apples가
외부 블럭의 apples를 shadowing한다는 것을 알 수 있따
최종적으로 외부 블럭의 apples는 변화가 없기 때문이다

Shadowing of global variables

이는 global variables도 마찬가지다

#include <iostream>

int value { 5 };

void test()
{
	std::cout << value << std::endl;
}

int main()
{
	std::cout << value << std::endl;
	int value {7};
    std::cout << value << std::endl;
    test();
    std::cout << ::value << std::endl;
	return 0;
}

위와 같으 경우 출력은 아래와 같다

5
7
5
5

global variable에 접근할 때 ::value 를 이용해서 접근할 수 있었다

Avoid variable shadowing

shadowing은 의도치 못한 에러를 발생시킬 수 있으므로
가급적 피하는 것이 좋다

단어장

inadvertent : 부주의, 고의가 아닌
advertent : 주의 깊은

profile
청룡동거주민

0개의 댓글