educative.io

Static variable

I thought static variable means that the variable won’t change at all?
but then why is it still affected by the function, what is the difference between static and normal variables then? I see no difference and I am confused


Course: Learn C from Scratch - Learn Interactively
Lesson: Automatic vs Static Variables - Learn C from Scratch

Hi @A_Huang
My name is Shahrukh Naeem. I hope everything is going well with you. Thank you for reaching out about this. I will try my best to answer your query!

A static variable is the one allocated “statically,” which means its lifetime is throughout the program run . It is declared with the ‘static’ keyword and persists its value across the function calls.

Let’s take an example:

#include <iostream>
using namespace std;
void func()
{
    static int static_var=1;
    int non_static_var=1;

    static_var++;
    non_static_var++;

    cout<<"Static="<<static_var<<endl;
    cout<<"NonStatic="<<non_static_var<<endl;
}

int main()
{

    int i;
    for (i=0;i<5;i++)
    {
        func();
    }
    return 0;
}

The above gives output as:

Static=2
NonStatic=2
Static=3
NonStatic=2
Static=4
NonStatic=2
Static=5
NonStatic=2
Static=6
NonStatic=2

A static variable retains its value while a non-static or dynamic variable is initialized to ‘1’ every time the function is called.

I hope that this guide is helpful. Remember that I am always available via message to help you with any difficulty you might encounter.

Regards,

Happy Learning :slight_smile: