函数范围内的静态变量和局部变量之间的差异
我正在尝试找到输入整数中的数字数量。 但它总是打印“数字:1”。 代替函数中的整数 i ,如果我使用“ static int i = 0;
”函数内部的工作原理。
而且我无法理解这种行为。
#include <stdio.h>
int func(int a, int i)
{
if (a != 0)
{
i++;
func(a / 10, i);
}
return i;
}
int main()
{
int a, c;
printf("Enter the No:");
scanf("%d", &a);
c = func(a, 0);
printf("No. of digits: %d", c);
return 0;
}
I am trying to find the number of digits in the input integer.
But it always prints "no. of digits: 1".
In place of getting integer i
from function, if I use "static int i = 0;
" inside the function it works perfectly.
And I can't understand this behavior.
#include <stdio.h>
int func(int a, int i)
{
if (a != 0)
{
i++;
func(a / 10, i);
}
return i;
}
int main()
{
int a, c;
printf("Enter the No:");
scanf("%d", &a);
c = func(a, 0);
printf("No. of digits: %d", c);
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的递归在每次呼叫时反复刷新您的功能的内存。
ts相同,它就像
全局变量
和local变量
之间的相同问题。当您不使用静态
时,对您功能的每个调用都会刷新您的变量i
并再次初始化。当您使用静态
时,变量i
将与仅使用一次语句的全局变量相同。Your recursion repeatedly refreshes the memory for your function at every call.
ts the same, it is like the same question between
global variable
andlocal variable
. When you do not usestatic
, every call to your function will refresh your variablei
and initialize it again. When you usestatic
, the variablei
will be the same as a global variable with just once statement.关于您关于静态的问题:
目前尚不清楚要在哪里使用
static int i = 0;
作为替代方案。在函数中(并删除函数arg i),它即使在函数退出后也将其保存在内存中。请参阅此问题参考。如果它不在函数之外,请查看这个问题供参考。
关于您的代码:
您的代码没有使用递归功能调用的结果。它既不存储在局部变量i中,也不直接返回。它简直就是丢失。请参阅下面的代码示例,可能是您想要的。
编辑:原始答案中的变量i是不必要的,所以我将其删除。
Regarding your question about static:
It is unclear where you want to use
static int i = 0;
as alternative.Inside the function, (and removing the function arg i) it becomes a variable that is kept in memory even after the function exits. See this question for reference. If it is outside of a function look at this question for reference.
Regarding your code:
Your code is not using the result of your recursive function call. It is neither stored inside the local variable i, nor returned directly. It is simply lost. See a code example below, that might be want you want.
EDIT: The variable i in the original answer was unnecessary, so I'll remove it.