C 如何减少 if 语句

标签 c

我对编程领域还比较陌生。我尝试过几种语言,但最终决定从 C 开始,因为它提供支持并且易于入门。我目前正在尝试编写一个简单的基于文本的征服类游戏。 有了这个,就有大量的地方或领土可供选择攻击,等等。我给每个区域一个数字 ID 1-50,这就是我的问题所在。我能想到的测试用户输入的 ID 的唯一方法是编写 50 个 if 语句,这是 super 乏味且烦人的。有更简单的方法吗?

  AttackTrue(){
int AmountOfTroops;
int TerrToAttack;
//List of territories with their id 
// example: int California = 1;
    printf("You have %d troops\n"); 
    printf("Enter the number of troops you want to use.");
            scanf(" %d",&AmountOfInfantry);
            printf("Enter the ID of the territory you want to attack.\n");
            scanf(" %d",&TerrToAttack);
            /*HERE IS WHERE ALL THE IF STATEMENTS WOULD GO*/
            }

}

最佳答案

您可以按照 JerryGoyal 的建议使用 switch case。 另一种方法是使用指向函数的指针数组:

void* (*funcLUT[50])(void*);

创建一个init函数来填充数组(最好有一个DoNothing()函数作为默认值)并根据ID调用该函数:

retValue = funcLUT[ID](data);

希望有帮助

关于C 如何减少 if 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30687358/

相关文章:

C 和内存中的带符号字节表示

c - 有没有办法识别 C 项目中所有未使用的全局变量?

c - 我对 malloc 和 realloc 的理解有什么问题?

c - Visual Studio 2015 中的警告 C4477

c - 有没有办法获取 .exe 中包含的静态链接函数并重用它们?

c - 通过递归反转字符串中的单词

未找到 C11 GCC threads.h?

c++ - GCC 编译时出现警告 : unknown escape sequence: '\040'

c - 操作数如何提升

c - IAR编译器 "stdio library"