只要我记得我已经避免使用switch语句.实际上,我不记得它曾经进入我的意识作为一种可能的做事方式,因为它早在我的头脑中钻了它只不过是转换语句中的一个错误.然而,今天我遇到了一些在设计中使用它的代码,这让我立刻想知道社区中的每个人都认为有关switch语句的漏洞.
这是编程语言应该明确不允许的东西(比如C#,但它提供了一种解决方法),还是任何语言的功能都足以留给程序员手中?
编辑: 我没有具体到达我的意思.我经常使用这种类型:
switch(m_loadAnimSubCt){
case 0:
case 1:
// Do something
break;
case 2:
case 3:
case 4:
// Do something
break;
}
Run Code Online (Sandbox Code Playgroud)
但是,我很担心这样的事情.
switch(m_loadAnimSubCt){
case 0:
case 1:
// Do something but fall through to the other cases
// after doing it.
case 2:
case 3:
case 4:
// Do something else.
break;
}
Run Code Online (Sandbox Code Playgroud)
这种方式只要大小写为0,1就会在switch语句中执行所有操作.我已经通过设计看到了这一点,我只是不知道我是否同意以这种方式使用switch语句.我认为第一个代码示例非常有用且安全.第二个似乎有点危险.
我试图计算字符串类中的字符数,但由于某种原因,程序完全跳过我的函数.这只是主程序的测试代码,它仍然给我相同的结果.怎么跳过计数器功能?
#include <iostream>
#include <string>
using namespace std;
void prompt(string& dna)
{
cout << "Input: ";
getline(cin, dna);
}
void counter(const string DNA,
int* a_count, int* t_count, int* c_count, int* g_count)
{
for (int i = 0; i < DNA.size(); i++)
{
if (DNA.at(i) == 'a')
{
*a_count++;
}
else if (DNA.at(i) == 't')
{
*t_count++;
}
else if (DNA.at(i) == 'c')
{
*c_count++;
}
else if (DNA.at(i) == 'g')
{
*g_count++;
}
}
}
int main()
{
string dna; …Run Code Online (Sandbox Code Playgroud)