Home > Software engineering >  Difference between static and local variable inside a function scope
Difference between static and local variable inside a function scope

Time:04-26

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;    
}

CodePudding user response:

your recursion just like repeating apply for memory for your function. As the same,it like the same question between global variable and local variable.When you not use static, your every call to your function will refresh your variable i and init it again.When you use static,the variable i will be the same as global variable with just once statement.

CodePudding user response:

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.

#include <stdio.h>

int func(int a, int i) {
    if (a == 0) {
        return 0;
    }
    return 1   func(a / 10, i 1);
}

int main() {
    int a, c;
    printf("Enter the No:");
    scanf("%d", &a);
    c = func(a, 0);
    printf("%d", c);
    return 0;
}
  • Related