gpt4 book ai didi

考虑给出的 `fork` 程序,以下程序打印 hello 多少次?

转载 作者:行者123 更新时间:2023-11-30 16:58:02 25 4
gpt4 key购买 nike

Please, consider the fork program given below:

下面的程序打印了多少次 hello?

main(int argc, char **argv) {
int i;
for (i=0; i < 3; i++) {
fork();
printf("hello\n");
}
}

“hello”消息总数 = 2 + 4 + 8 = 14 ( see question-1 at page-5 )。

<小时/>

下面的程序打印了多少次 hello?

#include <stdio.h>
#include <unistd.h>
main()
{
int i;
for (i=0; i<3; i++)
fork();
printf("hello\n");
}

“你好”消息总数 = 8 ( see question-4 at page-5 )。

在我看来,这两个程序是相同的。为什么解释/答案不同?

Can you explain, please?

最佳答案

此处,第一个程序中的 printf("hello\n”); 语句位于 for 循环内。

for (i=0; i < 3; i++) {
fork();
printf("hello\n”);
}

并且,第二个程序中的 printf("hello\n”); 语句位于 for 循环之外。

for (i=0; i<3; i++)
fork();//after semicolon printf is outside the for loop's block scope.
printf("hello\n");

这是两个给定代码之间的差异。

关于考虑给出的 `fork` 程序,以下程序打印 hello 多少次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39146501/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com