스코프(scope) : 변수가 유효한 범위
- 변수의 스코프(scope)는 해당 변수가 선언된 블록에서 유효하다. (블록은 중괄호({ })로 표시됨)
문제가 된 코드 : switch문 내에서 변수 itr을 정의함
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <set>
#include <map>
#include <algorithm>
using namespace std;
int main() {
enum {ADD = 1, ERASE, PRINT};
map<string, int> student;
int n, order, score;
string name;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> order >> name;
switch(order) {
case ADD:
cin >> score;
auto itr = student.find(name); // error
if (itr != student.end())
itr->second += score;
else
student.insert(make_pair(name, score));
break;
case ERASE:
student.erase(name);
break;
case PRINT:
auto itr = student.find(name); // error
if (itr != student.end())
cout << itr->second << '\n';
else
cout << "0\n";
break;
}
}
return 0;
}
※ C++의 스코프 규칙을 어김 (잘못된 접근)
** 컴파일러가 오류를 발생한 이유 **
: scope 규칙에 따라 한 블록 안에서 선언한 변수는 그 블록 범위 안에서 살아있어야 하는데 switch의 어떤 case안에서 변수를 선언하면 그 케이스 레이블에서만 살아있게 되니까 switch는 전체가 한 블록인데 스코프 규칙을 어겨서 컴파일러가 에러 띄운 것
수정한 코드
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <set>
#include <map>
#include <algorithm>
using namespace std;
int main() {
enum {ADD = 1, ERASE, PRINT};
map<string, int> student;
int n, order, score;
string name;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> order >> name;
auto itr = student.find(name); // 선언을 switch문 밖에서 함
switch (order) {
case ADD:
cin >> score;
if (itr != student.end())
itr->second += score;
else
student.insert(make_pair(name, score));
break;
case ERASE:
student.erase(name);
break;
case PRINT:
if (itr != student.end())
cout << itr->second << '\n';
else
cout << "0\n";
break;
}
}
return 0;
}
C++ > Control Structure
: Sequence Structure, Selection Structure, Loop Structure
1. Sequence Structure(순차 구조) : linear-instruction
- 조건문(conditional statements), 반복문(loop)이 없고, 코드가 순차적으로 실행되는 구조
2. Selection Structure(선택 구조) : if-else문, switch문
- 특정 조건이 충족되었을 때, 프로그램의 흐름을 특정 코드 블록으로 전환하는 것
▶ if-else와 switch 문의 차이점
둘 다 선택 문이며 특정 조건이 충족될 때 프로그램 흐름을 특정 문 블록으로 전송하는 데 사용하지만,
a) if-else문 : equality와 logical expression 모두 검사 가능
- integers, floating-point values, characters, booleans, etc.
b) switch문 : equality만 검사
- integer or character 데이터 타입
3. Loop Structure(반복 구조) : while문, do-while문, for문
(출처) https://www.scaler.com/topics/control-structure-in-cpp/