static vs constant in layman's language

closed account (1vf9z8AR)
Please tell me the difference between static and constant in easy language.

constant - read-only, value doesn't change.
static - exist during the whole run of the program, memory location doesn't change.
closed account (1vf9z8AR)
so if declare a static variable in one function i can use it another function?
No, not unless you pass it to the function or make it available by other means.
Basically, if you create a static variable in a function, you can use it every time the function is called, and the value will still be the same as the previous time the function got executed.
An example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>

void foo()
{
    static int x = 5; /*Create a static variable called x, and give it a value of 5*/
    std::cout << x << std::endl;
    ++x
}

int main()
{
    foo(); /*Prints '5'*/
    foo(); /*Prints '6', as the previous call to foo() incremented x by one.*/
    return 0;
}

Last edited on
closed account (1vf9z8AR)
thanks guys.
Topic archived. No new replies allowed.