I am doing research on static and const keywords.
Static: Use the static modifier to declare a static member, which belongs to the type itself rather than to a specific object.
const: You use the const keyword to declare a constant field or a constant local. This keyword specifies that the value of the field or the local variable is constant, which means that it can't be modified.
I would like to know about example when programmers would use static and const keywords.
const variables, or constant, would be used to declare a value that won't change or you want to prevent from being changed. For example, Pi could be declared as a constant in C++.
const double kPi = 3.14159265359;
static variables are a bit different. There is only one instance of the static variable that persists across classes\functions.
For example:
void foo()
{
static int bar = 0;
printf("%d\n", bar);
++bar;
}
int main()
{
int i;
for(i = 0; i < 5; ++i)
{
foo();
}
}
Would print:
0
1
2
3
4
Even though bar goes out of scope, its value is still in memory, so its only initialized once. Each time the foo() is called, that value gets incremented.
Edit:
To clarify, the compiler will actually reserve memory for the static variable within the assembly code that it produces. Additionally, the static keyword also tells the compiler to initialize the variable exactly once. The scope of the variable is the same (inside the foo function), but it is only initialized once in the above case. Automatic variables (such as int i) are pushed onto the call stack when the function is called.
(All of this is for Langage C++)
Hi, you can use const and static keywords in few cases, for exemple :
Const
First, used to say that the variable cannot be modified.
int main()
{
const int toto[4] = {0, 1, 2, 3};
return (0);
}
// We cannot modify toto after it declaration, why is it usefull? It keeps the state of your program design
Second, used to say that a method do not modify the object state.
class toto
{
int i;
public:
int geti() const;
}
// All getter in CPP use it. Why is it usefull? Developper who use the class know that he do not modify the object state
Third, used to say that the parameter pass to a function isn't modify by the function.
int function(const std::string &str)
{
// function cannot modify the object string pass in parameter
}
Static
First, used to say that a implemented function is know only inner a single file.
static int fct()
{
return (0);
}
// You can ony call function fct() if you are inner the file who it is implemented
Second, used to say that a argument or method is common to all object of the same class.
class toto
{
public :
static int getLol();
};
// Every object totoObj1, totoObj2 ... will call same function
Third and the last one, used to say that a variable do not change state between multiple call of the same function where it is declared
void fct()
{
static i = 0;
std::cout << ++i << std::endl;
}
// This function are going to print 1 then 2 then 3 ...
If you have any questions, you are welcome :)
If you want to have any variable/method to be available irrespective of an object you go for a static member but if you want the same to be unmodifiable as well then const is the solution. Following example can help you understand this.
In below example
PI is defined as a constant and can not/should not be changed
ONLINE holds number of users online, it can change but should be available irrespective of objects
public class Example
{
//PI should not be changed, with reasons known that it is a constant
public const double PI = 3.14;
//Users currently using the application
public static int ONLINE = 0;
public Example(){ ONLINE++; }
public void dispose(){ ONLINE--; }
public static int loggedInUsers(){ return ONLINE; }
public void GetArea(int radius){return PI*radius*radius; }
}
Related
I have recently run into some trouble while trying to perform the following logic:
static const int size = getSize();
int getSize() {
return 50;
}
The error I have received is initialiser element is not constant
Having read online I understand that this issue is because the compiler evaluates the static const expression at compilation and therefore cannot know what the value is supposed to be.
My question is how do I get around this?
If I have a library that contains many functions but they all require this logic how are they supposed to use it without having to calculate it each time?
And even if they have to, what if the logic itself can change throughout runtime but I only ever want the first value I receive from the function?
Perhaps I should clarify that the logic in getSize is just an example, it could also contain logic that retrieves the file size from a specific file.
Unlike in C++ you cannot initialize global variables with the result of a function in C, but only with real constants known at compile time.
You need to write:
static const int size = 50;
If the constant must be computed by a function you can do this:
Dont declare static const int size = ... anymore, but write this:
int getSize()
{
static int initialized;
static int size;
if (!initialized)
{
size = SomeComplexFunctionOfYours();
initialized = 1;
}
return size;
}
int main(void)
{
...
int somevar = getSize();
...
That way SomeComplexFunctionOfYours() will be called only once upon the first invocation of getSize(). There is a small price to be paid: each time you invoke getSize(), a test needs to be performed.
Or you can initialize it explicitely like this, but then size cannot be const anymore:
static int size;
void InitializeConstants()
{
size = SomeComplexFunctionOfYours();
}
int main(void)
{
InitializeConstants();
...
int somevar = size;
...
The compiler needs to know the value of your constant variable at the compilation time, because its a constant.
Also you can't initialize a variable with a function.
You should do something like this :
#define SIZE 50
static const int size = SIZE;
If I convert const int to int inside a void it works.
But when I create an extern const int it doesn't.
void ReadFromEpprom()
{
int Start = 343;
const int End=Start; //This works
}
Example 2
Header File
extern const int End;
Source file
const int End;
void ReadFromEpprom()
{
int Start = 343;
End=Start; //This doesn't work
}
In second situation I get error:
(364) attempt to modify object qualified const
How can I solve this?
Should I make it with another way?
When you declare a constant variable this means the variable will not change.So it makes sense that constant variables must be initialized immediately.You are doing this in your first example which is correct.In your second example you have a constant variable and then you are trying to modify it's value.This is incorrect since the variable is already constant.
The extern here is a red herring.
If you use const int End then you need to initialise End at the point of this declaration. That's because it's const.
So const int End = Start; works fine, but const int End; is not syntactically viable.
In C you can't arrange things so you have a const at global scope and a function that sets the value at run-time. But what you could do is embed the value in a function (as as static), and call that function to initialise and subsequently retrieve the value.
Initialiazation versus assignment:
A const object can be initialized (given a value at the declaration), but not assigned (given a value later).
This is initialization, and "works". It is initialization the local variable End that exist inside ReadFromEpprom().
void ReadFromEpprom()
{
...
const int End=Start; //This works
End=Start; attempts to assigned End that exist at file scope, outside of ReadFromEpprom(). const objects cannot be assigned.
const int End;
void ReadFromEpprom()
{
...
End=Start; //This doesn't work
}
How can I solve this?
Let external code to read localEnd via a function ReadEnd(), yet allow local code to write localEnd.
static int localEnd;
int ReadEnd() {
return localEnd;
}
void ReadFromEpprom() {
int Start = 343;
localEnd = Start;
}
I agree with all the other answers.
It seems that you want to initialize a const value with a value that will be determined at run time, which is impossible.
What you can do is two workarounds.
Remove const. Add a comment near its definition that the variable is set only once in the very beginning.
Use a function instead of a const int variable; implement the "run code only once" idea inside this function.
Header file:
int CalcEnd();
Source file:
int CalcEnd()
{
static int init_done = 0;
static int result;
if (!init_done)
{
result = 343; // or any complex calculation you need to do
init_done = 1;
}
return result;
}
Note how the function uses static variables and logic to do initialization only once.
If you use the function idea, and don't want to remember typing the parentheses in the function call (CalcEnd()), you can define a macro:
#define End MyCalcEnd()
This will make it appear as if End were const int variable, when actually it's a function call. This usage of macros is controversial, use it only if you are sure it will not lead to confusion later.
I am writing a data mashing function where I'm modifying audio data over time for a sort of dynamic bit-crusher audio filter. It is convenient for me to use static variables because their values carry over between function calls and this helps me achieve some interesting time-based effects by incrementing and so forth across rendering callbacks.
For example, one effect uses a sin function to modulate some sound effect over time. Like so:
void mangle(float * data, int n) {
static bool direction = false;
static float bottom = 0;
static float top = n;
static float theta = 0;
theta += 5;
// data = sin(theta) etc..
So I wish theta to be initialized once and than modified over time. Likewise, top wants to be static variable because I modify it later in the function also. In addition, top should take on the value of parameter n because n changes based on program state. But when I go to assign n to top, I get the compiler error
Initializer element is not a compile-time constsant.
Is there a way to assign a parameter to a static variable? Is there another way to accomplish what I want without static variables? I am aware I could use instance variables but I find that to be too much.
static variables are initialized before the program execution begins, so you cannot use a variable value to initialize a static variable. You'll need a compile-time constant value to initialize the static variable.
Quoting C11 standard, chapter §6.2.4, Storage durations of objects (emphasis mine)
[..] or with the storage-class
specifier static, has static storage duration. Its lifetime is the entire execution of the
program and its stored value is initialized only once, prior to program startup.
However, you can always assign a new value to the static variable.
That said, coming to the initialization part, as per chapter §6.7.9,
If an object that has static or thread storage duration is not initialized
explicitly, then
- ...
- if it has arithmetic type, it is initialized to (positive or unsigned) zero
- ...
so, you need not initialize the static floats explicitly to 0. You can assign any value, whatsoever later in the code.
In your case, top is a local static variable.
It is like global static variable and global variable that they all have static storage duration and they have value before the code startup.
The reason you have error similar to this case:
int a;
int b = a; \\initializer is not a constant
int main() {
...
}
With your purpose, use top as a global variable is a right way to go.
What you should do is create a struct that holds the data that is needed across calls and pass a pointer to the struct to the function. If you wnat to get fancy, you can create functions that allocate, initialize and free such a struct (and the user of the functions never needs to know what the contents of the struct are.
Something like:
struct mangle_t {
bool direction;
float bottom;
float top;
float theta;
};
struct mangle_t* mangle_open(void)
{
struct mangle_t* m = malloc(sizeof *m);
if (m) {
memset(m, 0, sizeof *m);
}
return m;
}
void mangle_close(struct mangle_t* m)
{
free(m);
}
void mangle(struct mangle_t* m, float * data, int n) {
m->top = n;
m->theta += 5;
}
As far as assigning a parameter to a static variable, you can just perofrm the assignment like any other variable (however, not as an initialization in the variable's declaration - that only happens once).
I'm not sure if you want to initialize top once and then keep it, but if so, this is what I would do:
void mangle(float *data, int n) {
static float top = -1; // Assuming that n will never be -1
if (top == -1)
top = n;
// .....
}
If you don't need to keep the value of top over function calls, there is no need to declare it static.
I was looking for a function to do some audio effect, and I found one written in C.
Inside this function, some variables are declared as Static. I am confused, I thought Static means these variables are not visibles to other files. But since they are declared inside inside a function, they are already not visible to other files.
What am I missing ?
static inside a function means that it will hold its value the next time the function is called.
For example,
int foo() {
static int i = 0;
printf("%d\n", i);
i++;
}
int main() {
foo(); // Prints 0
foo(); // Prints 1
}
What are the possible effect of returning a static type data. And when should we actually use it?
static ssize_t
my_read(int fd, char *ptr)
{
//code from Stevens Unix Network programming.
if (something)
return (-1)
if (something else)
return (0)
return (1)
}
why static here?
Thanks.
The function is static, not the return type. This means that its name is only visible from within the current compilation unit, which is used as an encapsulation mechanism.
The function can still be called from elsewhere through a function pointer, however.
See also this discussion on the general static keyword for more context.
We use static data type when returning a pointer to a variable created in called function.for e.g
float * calculate_area(float r)
{
float *p;
static float area;
p=&area;
area=3.14*r*r;
return p;
}
If you would make area as automatic variable i.e without any type qualifier it would be destroyed when control returns from called function.When declared as static you could correctly retrieved the value of area from main also.Thus it in order for it to persists its value we make it as static.
By using static , Access to static functions is restricted to the file where they are declared
Another reason for making functions static is to reuse the same function name in other files.
//file1
static void fun1(void)
{
cout<<"file1";
}
// file2
// now if we include file1 and use fun1 in file2 , it
// will show “undefined reference to `fun1’” error as
// it fun1 is defined static
int main(void)
{
fun1();
getchar();
return 0;
}