在main()函数中,case绕过了局部变量的初始化。
代码
#include <iostream.h>
#include <conio.h>
#include <string.h>
int
main()
{
int mat1[2][2], mat2[2][2], mat3[2][2];
cout << "Enter the elements in the first matrix";
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
cin >> mat1[i][j];
}
}
cout << "\n\nEnter the elements of the second matrix";
for (int k = 0; k < 2; k++) {
for (int l = 0; l < 2; l++) {
cin >> mat2[k][l];
}
}
cout << "\n\nsaved......";
int choice;
cout << "\n\n\nFor adding these two matrices,press 1";
cout << "\nFor subtracting these two matrices,press 2";
cin >> choice;
switch (choice) {
case 1:
cout << "The addition of the two matrices will yield";
for (int a = 0; a <= 1; a++) {
for (int b = 0; b <= 1; b++) {
mat3[a][b] = mat1[a][b] + mat2[a][b];
}
}
break;
case 2:
cout << "The subtraction of the two matrices will yield";
for (int c = 0; c <= 1; c++) {
for (int d = 0; d <= 1; d++) {
mat3[c][d] = mat1[c][d] - mat2[c][d];
}
}
break;
}
getch();
return 0;
}
我发现将case(s)的代码放入大括号中可以消除这个错误,但是我对错误本身和case语句中大括号的要求感到困惑。(我知道我没有使用新的编码规范,如,std命名空间等等,因为我是在Turbo C ++编译器中编写的,所以恳请给出简明扼要的答案。)