Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C/C++ The purpose of static const local variable [closed]

Tags:

c++

c

static

In C and C++, what is the advantage of making a local const variable static? Assuming the initialization does not use other variables, is there any difference between preserving the value between calls, and setting the same constant value each call?

Could a valid C compiler ignore the static?

In C++, it avoids the construction/destruction between calls, but could there be any other benefit?

like image 809
yukon Avatar asked Feb 20 '13 23:02

yukon


People also ask

What is the use of static const in C?

“static const” is basically a combination of static(a storage specifier) and const(a type qualifier). The static determines the lifetime and visibility/accessibility of the variable.

What is the purpose of static keyword when declaring a local variable?

When applied to a local variable, the static keyword defines the local variable as having static duration, meaning the variable will only be created once, and will not be destroyed until the end of the program.

What is the purpose of const in C++?

The const keyword specifies that a variable's value is constant and tells the compiler to prevent the programmer from modifying it. In C, constant values default to external linkage, so they can appear only in source files.

Can we use static const in C?

const means that you're not changing the value after it has been initialised. static inside a function means the variable will exist before and after the function has executed. static outside of a function means that the scope of the symbol marked static is limited to that . c file and cannot be seen outside of it.


1 Answers

It doesn't take up stack-space may be a benefit if you have something like:

static const double table[fairly_large_number] = { .... };

Obviously, cost of construction can also be substantial enough that if the function is called a lot, there's good value in only constructing the object once.

like image 79
Mats Petersson Avatar answered Sep 17 '22 10:09

Mats Petersson