需要对此代码进行一些解释

Need some explanation for this code

我找到了这个 c99 代码。谁能解释一下这里到底发生了什么?

for(char const * i = "*****";printf("%s\n",i + 4) < 6;i--);

让我剖析那一行:

for(char const * i = "*****";printf("%s\n",i + 4) < 6;i--);

for 循环条件的第一部分:char const * i = "*****"; 只是一个指向 5 星字符的指针。 i+1 会指向 ****i+2 会指向 *** 等等。

第二部分打印给定的星星数:printf("%s\n",i + 4)。通常在 for 循环的这一部分,我们使用类似 i < n 的东西。在这里,我们得到的结果不是 i,而是 printf

看看man 3 printf就明白了:

RETURN VALUE Upon successful return, these functions return the number of characters printed (excluding the null byte used to end output to strings).

所以基本上我们 printf i 字符串的较小部分直到 printf returns 6 作为打印的字符数。

这是它打印的内容:-

*
**
***
****
*****

要记住的要点:-

  • printf returns 打印的字符数
  • for 循环执行直到条件计算结果为真
  • i 被初始化为 const 字符串中的最后一个开始,并且每次迭代向左移动 1 个星号
This might make it more clear:

char*i = "12345";
int charsPrinted = printf( "%s\n", i + 4 );
while ( charsPrinted < 6 )
{
    i--;
    charsPrinted = printf( "%s\n", i + 4 );
}

但是很可能会崩溃。要打破循环,charsPrinted 必须达到 6,这意味着 i 不再指向字符串开头。在这一点上它不是真的有效。它可能有效,但要视情况而定。没有崩溃,这将被打印:

5
45
345
2345
12345