字符指针的预增量

Preincrement in character pointers

我在玩弄数组指针的概念。我写了这个简单的程序:

#include <stdio.h>

int main (int argc, char **argv){
    char s[] = "Hello world!\n";
    char *i;
    for (i = s; *i; ++i){
        printf(i);
    }
    return 0;
}

这给出了非常有趣的输出:

Hello world!
ello world!
llo world!
lo world!
o world!
 world!
world!
orld!
rld!
ld!
d!
!

然而,当我写这篇文章时,我的印象是输出将从第二行开始。原因是,在 for 循环中,我使用了预递增符号。 i 设置为 s 的开头,检查布尔条件并成立,然后 i 递增并执行块。

这是我的印象,但显然这是错误的,因为块在 i 递增之前执行。我使用 post 递增符号重写了程序,得到了完全相同的结果,这证实了我的假设。如果是这样,那么他们在这个程序中是如何区别对待的?

for循环的递增表达式在循环体之后执行。针对您的情况

for (i = s; *i; ++i){
  printf(i);
}

类似于

i = s;       // loop init
while (*i)   // loop condition
{
  printf(i);
  ++i;       // loop increment
}

i 在块执行后递增。

试试这个:

for(int i = 0; i < 5; ++i )
{
  printf("\n %d",i);
}
for (initialization; condition; increase) statement;

这个 for 的工作方式如下:

  1. initialization 被执行。通常,这会声明一个计数器变量,并将其设置为某个初始值。这是在循环开始时执行一次。

  2. condition 已勾选。如果是true,则继续循环;否则,循环结束,跳过statement,直接进入第5步。

  3. statement 被执行。像往常一样,它可以是单个语句,也可以是用花括号 { } 括起来的块。

  4. increase被执行,循环回到第2步

  5. 循环结束:继续执行它之后的下一条语句。

后增量和前增量没有区别,因为increase无论如何都是分开执行的。

相当于

for( a ; b ; c )
{
  statements
}

a ;
while( b ) 
{
  statement
  c ;
}

++i ;
i++ ;

是一样的东西,因为我只求值而没有求值

i is set to the beginning of s, the Boolean condition is checked and it holds true, then i gets incremented and the block executes.

不完全是。实际语法是

  1. i设置为s

  2. 开头
  3. 布尔条件已检查

    2.1。如果成立,块执行,

    2.2。否则跳出循环。

  4. 然后 i 递增并继续第 2 步。

注意:在此特定情况下,pre 和 post 递增到 i 不会产生任何影响。

Reason being, in the for loop, I use a pre-increment notation. i is set to the beginning of s, the Boolean condition is checked and it holds true, then i gets incremented and the block executes.

没有。 i 在 块执行后递增

I rewrote the program using a post-increment notation and got exactly the same result which confirms my hypothesis. If that is the case, then how are they treated differently in this program?

他们不是。 Post-增量或预增量不会造成盲目差异。这两者之间的区别在于表达式 i++++i 的结果(即,它的计算结果是前一个值还是新值?)。它不会神奇地改变封装控制结构的整个流程。增量表达式的计算结果被丢弃,所以只要您提供一个导致增量 i.

的表达式,您做什么并不重要

是这样的:

int main()
{
    int x = 5;
    int y = 5;

    int a = x++;
    int b = ++y;
}

将导致ab的值不同,因为使用了增量表达式的结果,而以下程序:

int main()
{
   int x = 5;
   x++;
}

int main()
{
   int x = 5;
   ++x;
}

相同。