开关函数和指针(见代码)

Switch function and pointers(See the code)

本文关键字:代码 指针 函数 开关      更新时间:2023-10-16

今天我正在学习和测试在C++中使用switch语句的不同形式;然后我编写了这段代码来创建一个函数,允许用户输入三个字符,其中两个是大小写,一个是比较字符(Main input(。我决定使用指针,因为我不能为案例使用变量,但我的方法不起作用,我只是不明白为什么?因为使用指针实际上意味着我指向已经定义的地址的值!

这是错误:


[Error] 'iloc' cannot appear in a constant-expression
[Error] '*' cannot appear in a constant-expression

这是代码:

#include <iostream>
using std::cout;
using std::cin;
void switch_function(char i, char j, char c){
//inputing values by the user
cout <<"Insert i(char): ";
cin >> i;
cout <<"Insert j(char): ";
cin >> j;
cout <<"Insert c(char) "<< i <<" Or "<< j <<": ";
cin >> c;
//declaring pointers
char * iloc;
char * jloc;
char * cloc;
//registering memory adresses
iloc = &i;
jloc = &j;
cloc = &c;
//switch function
switch(*cloc){
case *iloc:
cout << i;
break;
case *jloc:
cout << j;
break;
}
}
int main(){
//s and f characters are the cases and the third f is the main user input.
switch_function('s', 'f', 'f');
cout <<"n";
int location;
int * target;
target = &location;
cout << &location;
cout <<"n"<< target + 1;
}
case *iloc:

是不可能的。case只接受编译时已知的常量。在这种情况下使用if/else if