使用 while 块什么都不做是件坏事吗?

编程入门 行业动态 更新时间:2024-10-17 17:18:41
本文介绍了使用 while 块什么都不做是件坏事吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我目前正在完成C 编程语言"中的练习.这是我的解决方案之一:

I'm currently working through the excercises in 'The C Programming Language'. Here's one of my solutions:

int c;

while ((c=getchar()) != EOF) {

if (c == ' ') {

    while ((c = getchar()) == ' ')

    {}  // do nothing?

    putchar(' ');

}

putchar(c);

}

我在这里找到了一些与我和我的完全不同的解决方案使用一个额外的变量来跟踪正在发生的事情,而我只是使用一个 while 循环来跳过所有空间.我的解决方案感觉有点混乱,因为在花括号之间没有任何东西的 while 循环似乎有点hackish.我想知道是否有任何充分的理由不这样做?感谢您的任何建议:-)

I found some solutions here that are quite different to mine and use an extra variable to keep track of what's going on, whereas I just use a while loop to skip through all the spaces. My solution feels a bit messy, as it seems bit hackish to have a while loop with nothing between the curly braces. I was wondering if there are any good reasons not to do this? Thanks for any advice :-)

推荐答案

完全没有 - 我相信你会在 K&R 中找到类似这样的无用循环,所以这与它得到的一样正式.

Not at all - I believe you'll find do-nothing loops like these in K&R, so that's about as official as it gets.

这是个人喜好的问题,但我更喜欢这样的无操作循环:

It's a matter of personal preference, but I prefer my do-nothing loops like this:

while(something());

其他人更喜欢将分号放在单独的行上,以强调它是一个循环的事实:

Others prefer the semicolon to go on a separate line, to reinforce the fact that it's a loop:

while(something())
  ;

还有其他人更喜欢使用没有任何内容的括号,就像您所做的那样:

Still others prefer to use the brackets with nothing inside, as you have done:

while(something())
{
}

这一切都是有效的——你只需要选择你喜欢的风格并坚持下去.

It's all valid - you'll just have to pick the style you like and stick with it.

这篇关于使用 while 块什么都不做是件坏事吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-26 03:38:45,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1128951.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:什么都不   坏事   做是件

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!