【发布时间】:2019-10-13 12:44:14
【问题描述】:
当调用并运行以下函数时,如果满足初始的“if”条件,则程序按预期运行;反复。如果最初的“if”条件不满足,程序会继续运行 else 语句,但会陷入无限循环。
为什么?
#include <stdio.h>
#include <string.h>
int num_func();
int main()
{
num_func();
return 0;
}
int num_func()
{
int num;
char yn[1];
printf("Please enter an integer value: ");
if (scanf("%d", &num) == 1)
{
printf("The value you entered is: %d. Is this correct? ", num);
scanf("%s", &yn);
if (strcmp(yn, "y") == 0) {
printf("Great! \n");
}
else if (strcmp(yn, "n") == 0) {
printf(":( \n");
}
else {
printf("Illegal Entry. \n");
}
}
else {
printf("You were told to put in a number!");
}
num_func();
}
我也有兴趣了解如何制作 num 和 yn[1] 全局变量,以便 num_func() 可以访问它们而无需每次运行都分配内存。如果你能解释一下,我将不胜感激。
【问题讨论】:
-
因为你递归地调用函数本身,所以它会“永远”重复(或者如果在编译期间没有启用尾递归优化,直到它溢出堆栈)。
-
但是 num_func 放在 if else 语句之外,当满足其中任何一个条件时,编译器不应该从头开始运行 num_func 而不是通过 else 语句循环吗?
-
函数中没有返回语句,所以它永远不会提前退出。 num_func() 将在 if 或 else 语句执行后被调用,无论满足哪个条件。
-
我不明白
-
程序按顺序运行。为什么你认为 num_func 中的最后一条语句(它本身是对 num_func 的另一个调用)不会被执行?
标签: c