× Home
Next Lec → ← Previous Lec

Static variables

But before that let's do a recap

Local variables

  • Scope is a region of the program where a defined variable can exist and beyond which it cannot be accessed
  • Variables which are accessed inside a function or a block are called local variables.
  • They can only be accessed by the function they are declared in!
  • They are inaccessible to the functions outside the function they are declared in!

Global variables

  • These are the variables defined outside the main method.
  • Global variables are accessible throughout the entire program from any function.
  • If a local and global variable has the same name, the local variable will take preference.

Formal Arguments

  • These variables are treated as local variables with in a function.
  • These variables take precedence over global variables.

Now see Static variables in C

Syntax

static data_type name = value;

static int harry = 7;
Even after using this variable it will still take some memory that's why global and static variables are not recommended.

#include <stdio.h> int func1(int b) { static int myvar = 0; printf("The value of myvar is %d\n", myvar); myvar++; return b + myvar; } int main() { int b = 100; int val = func1(b); //here myvar is 0 as this runs first time func1(b); //when function is called 2nd time the value of myvar become 1 even
though insisde the function // it is initialized as 0 which mean that it forget the initalization // printf("The value of func1 if %d",func1(b)); return 0; }