繁体   English   中英

printf(“%d”,i ++)和i ++有什么区别? 的printf(“%d”,i)的?

[英]What's the difference between printf(“%d”,i++) and i++; printf(“%d”,i)?

我正在Linux中学习fork(),对我来说,两个执行结果不同的程序完全相同:

第一个结果为“正常”,父子进程交替运行:

  6 int main(void){
  7         int pid;
  8         int i = 0;
  9         pid = fork();
 10         if(pid != 0){
 11                 while(1)
 12                         printf("a%d\n",i++);
 13         }
 14         
 15         else{   
 16                 while(1){
 17                         printf("b%d\n",i++);
 18                 }
 19         }
 20 }

$./test1.out
``` ```
b670071
a656327
b670072
a656328
b670073
a656329
b670074
a656330
b670075
a656331
b670076
a656332
b670077
a656333
b670078
a656334
b670079
a656335
b670080
a656336
b670081
```

但是第二个结果却完全不同:

  4 int main(void){
  5         int pid;
  6         int i=0;
  7         pid = fork();
  8         if(pid != 0){
  9                 while(1)
 10                         i++;
 11                         printf("a%d\n",i);
 12 
 13         }
 14 
 15         else{
 16                 while(1){
 17                         i++;
 18                         printf("b%d\n",i);
 19                 }
 20         }
 21 }


 $./test2.out
``` ```
b811302
b811303
b811304
b811305
b811306
b811307
b811308
b811309
b811310
b811311
b811312
b811313
b811314
b811315
b811316
b811317
b811318
b811319
b811320
b811321
b811322
b811323
b811324
b811325
b811326
b811327
b811328
b811329
b811330
``` ```

看起来只有子进程正在运行!

我认为您的第二个代码示例是:

int main(void){
     int pid;
     int i = 0;
     pid = fork();
     if(pid != 0){
             while(1)
                     i++;
                     printf("a%d\n",i);
     }

     else{   
             while(1){
                     printf("b%d\n",i++);
             }
     }
}

等价于

int main(void){
     int pid;
     int i = 0;
     pid = fork();
     if(pid != 0){
             while(1) {
                     i++;
             }
             // Unreachable code
             // vvvvvvvvvvvvvvvvvvv
                     printf("a%d\n",i);
     }

     else{   
             while(1){
                     printf("b%d\n",i++);
             }
     }
}

因此,将永远不会打印a*****

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM