Search code examples
cfunctionpointersmemory-addressstatic-variables

c programming using a static variable and then pointing to it ? possible?


In c when creating and returning the address in a static variable inside a function would it be the same as initializing a simple

int sNum2 = 0 ; int * temp = &sNum2;

? static will basically have it's own allocated size in the memory right?

and i could just point to it from the staticNum function from now?

Maybe is not a good practice but is it ok to use?

 int * staticNum(){
  int static sNum=0;
  int * temp=&sNum;
  sNum++;
  return temp;
}

Solution

  • This is valid code.

    A static variable, whether declared at file scope or inside of a function, has full program lifetime. That means its address will always be valid and can be safely dereferenced at any point in the program.