Mulder5 2020. 9. 9. 00:08
반응형

전통적인 반복문의 사용 예는 아래 예의 첫번째 for문과 같다.

struct Person
{
    float weight;
    float height;
};

Person persons[] = {
        Person{70.f, 181.f},
        Person{56.f, 167.f}
    };

 for (int i = 0; i < 2; ++i)
 {
     cout << persons[i].weight << persons[i].height << endl;
 }
 for (Person person : persons)
 {
    cout << person.weight << person.height << endl;
 }

그리고 범위 기반 For문은 그 두번째의 예이다. 대단히 간결한 코드를 만들 수 있는 것이 장점이다. 하지만 사용에 있어서 주의할 점은 복사가 이뤄진다는 점이다.

for (Person person : persons)
{
    person.weight = 0.f;
    
}
for (Person person : persons)
{
    cout << person.weight<< "  " << person.height << endl;
}

위의 코드에서 weight를 모두 0으로 변견한 것으로 보이지만 결과적으로는 변경되지 않았다. 여기서 정상적으로 weight를 변경하기 위해서는 다음과 같이 수정해준다.

for (Person& person : persons)
{
    person.weight = 0.f;
    
}
for (Person person : persons)
{
    cout << person.weight<< "  " << person.height << endl;
}

이제 정상적으로 변경된 것을 볼 수 있다. 범위 기반 for를 사용하면 복사가 이뤄진다는 점이 중요하다.

반응형