将复合语句放在for循环的条件中

Flo*_*ris 5 c for-loop

我有一个人为的例子来演示特定功能的请求 - 我想知道是否有人有一个聪明的技巧来做到这一点.

以下是一个经常遇到的问题:

"打印一系列数字;在它们之间打印一个空格,并在末尾打印回车(但没有空格).

显而易见的解决方案是使最后(或第一)语句成为特例.我正在考虑如何使这更有效/更紧凑.

蛮力:

for(ii=0; ii<4; ii++) {
  printf("%d", ii);
  if(ii<3) printf(" "); else printf("\n");
}
Run Code Online (Sandbox Code Playgroud)

请注意,这涉及对条件的两次评估.

展开:

for(ii=0; ii<3; ii++) {
  printf("%d ", ii):
}
printf("%d\n", ii);
Run Code Online (Sandbox Code Playgroud)

利用ii我们离开循环时最后一次增加的事实.

我想要的功能

ii = 0;
while(1) {
  printf("%d", ii);
  ii++;
  if(ii<3) printf(" "); 
  else {printf("\n"); break;}
}
Run Code Online (Sandbox Code Playgroud)

我想知道是否有可能在for声明中完成这项工作.我修改了一下,发现以下工作(有点令我惊讶......它确实需要括号,而且它?:,运算符之间很难读- 请参阅http://codepad.org/wFa2YwCg):

for(ii=0; (ii<3)?(printf("%d ",ii),1):(printf("%d\n",ii),0);ii++);
Run Code Online (Sandbox Code Playgroud)

我基本上把evaluate this conditionfor循环的一部分变成了一个execute this statement for most of the loop, and this other one for the last pass声明.

我想知道是否有更好的方法来做到这一点 - 既高效又可读?

Bat*_*eba 2

[在很多方面,这个问题应该结束,因为它是基于意见的。]

这个问题经常出现。我总是选择一种能够最大限度地减少迭代部分中的指令的解决方案。

{ /*don't pollute the outer scope with ii*/
    int ii;
    for (ii = 0; ii < 3; ++ii/*I've always preferred this to ii++*/) {
        printf("%d ", ii);
    }
    printf("%d\n", ii);
}
Run Code Online (Sandbox Code Playgroud)

三元数、if语句只会混淆事物。在我看来。