int foo(char c)
{
switch(c)
{
case '1':
return(1);
case '2':
return(2);
}
}
int main()
{
cout << foo('a');
}
此程序打印97。
**如果没有开关盒匹配,它会输出ASCII值作为输出。 如果没有一个案例匹配**
,为什么函数返回ASCII值答案 0 :(得分:2)
您的程序行为未定义:您必须在返回int
(main
除外)的任何函数上具有显式返回值。
(您似乎观察到的是堆栈损坏; 97是您作为函数参数传递的小写字母a
的ASCII值。)
答案 1 :(得分:1)
int foo(char c) {
switch(c) {
case '1':
return(1);
case '2':
return(2);
//code to execute if 'c' does not equal the value following any of the cases
default:
return(-1);
}
}
int main() {
cout << foo('a');
}
OR
// simple char to int without switch
int foo(char c) {
/*
// reject unwanted char
if (c=='a') {
return -1;
}
*/
// convert char to int
return (int)c;
}
答案 2 :(得分:1)
你在这里有UB。 foo
函数会获得一个它无法处理的输入,因为您的任何一个案例都不支持输入'a'
。可能发生的事情(如果我可以尝试在您的具体情况下解释这个UB)是foo
返回它被转换为int
的输入,这意味着cout << (int)('a');
对于此类情况,您的开关案例应包含default
,例如:
int foo(char c)
{
switch(c)
{
case '1':
return(1);
case '2':
return(2);
default:
return (-1); // indicates error!!
}
}
int main()
{
int tmp = foo('a');
if (tmp != -1)
cout << tmp;
else
cout << "bad input";
}