如何在 C 中创建 !default 情况
在微控制器程序上,我有一些指令,我想对开关中除默认值之外的每种情况执行这些指令。但是,我不想为每种情况编写函数调用或使用宏。
因为这是针对以 3-7Mhz 运行的微控制器,所以速度和代码空间非常重要。 例如:
switch(letter)
{
case a:
ShowApple();
printf("You entered an english letter.");
break;
case b:
ShowBananna();
printf("You entered an english letter.");
break;
...
case z:
ShowZebra();
printf("You entered an english letter.");
break;
default:
printf("You did not enter an english letter. Silly human!");
break;
}
On a micro-controller program I have a few instructions that I would like to execute for every case in a switch except the default. I do not, however, want to write a function call or use a macro for every case.
Because this is for a micro-controller running at 3-7Mhz, speed and code space are important.
For example:
switch(letter)
{
case a:
ShowApple();
printf("You entered an english letter.");
break;
case b:
ShowBananna();
printf("You entered an english letter.");
break;
...
case z:
ShowZebra();
printf("You entered an english letter.");
break;
default:
printf("You did not enter an english letter. Silly human!");
break;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我会为此下地狱...
I'm going to go to hell for this...
为什么不使用由字母索引的函数指针数组而不是
switch
?这将更加节省空间和速度。而且,在我看来,更具可读性。Why don't you use an array of function pointers indexed by a letter instead of
switch
? That would be both more space and speed efficient. And, IMO, more readable.如果它确实是每种情况下的最后一条语句,您可以简单地使用 if 语句随后执行它:
If it's really the last statement in each case, you could simply execute it afterward using an if statement: