cstaticinline

Behaviour of static keyword in inline function


I have belows test program

#include<stdio.h>
inline int func ()
{
static int a = 10;
a++;
return a;
}

int main()
{
int x,y,z;
x=func();
printf("x is %d\n",x);
y=func();
printf("y is %d\n",y);
z=func();
printf("z is %d\n",z);

return 0;
}

When i run i get op as

x is 11
y is 12
z is 13

As inline function means programmer has requested that the compiler insert the complete body of the function in every place that the function is called, rather than generating code to call the function in the one place it is defined

So does not o/p should be

x is 11
y is 11
z is 11

Solution

  • Your idea of the inline keyword is not entirely correct. Since C99 inline simply tells the compiler that it mustn't necessarily emit the code for the function in a compilation unit that sees it. It avoids "multiply defined symbols" errors through linking.

    To your question about static declarations inside inline functions: C99 just forbids them. So your problem doesn't occur with conforming code.

    You may be interested in some reading about inline and C99

    Also some nitpick, function declarations for functions that don't receive parameters should use void as a declaration list. Declarations with () refer to functions with an arbitrary number of parameters.