I've noticed that programmers make variables const
and static
. I understand what these keywords do, but I have no idea why they use them.
Example 1
from The Official Guide to Learning OpenGL, Version 1.1 Chapter 2
static GLint vertices[] = {25, 25,
100, 325,
175, 25,
175, 325,
250, 25,
325, 325};
static GLfloat colors[] = {1.0, 0.2, 0.2,
0.2, 0.2, 1.0,
0.8, 1.0, 0.2,
0.75, 0.75, 0.75,
0.35, 0.35, 0.35,
0.5, 0.5, 0.5};
glEnableClientState (GL_COLOR_ARRAY);
glEnableClientState (GL_VERTEX_ARRAY);
glColorPointer (3, GL_FLOAT, 0, colors);
glVertexPointer (2, GL_INT, 0, vertices);
Why in the world do these arrays have to be static if they're only being used in this single object instance?
Example 2
from OpenGL Programming on wikibooks tutorial 1
GLuint fs = glCreateShader(GL_FRAGMENT_SHADER);
const char *fs_source =
"#version 120 \n"
"void main(void) { "
" gl_FragColor[0] = 0.0; "
" gl_FragColor[1] = 0.0; "
" gl_FragColor[2] = 1.0; "
"}";
glShaderSource(fs, 1, &fs_source, NULL);
The fs_source char array doesn't get changed after it gets set. But is it absolutely necessary to make it constant? Does it increase performance?
Yes, usually, it does increase performance, though not necessarily in the way you imagine.
With these hints, the compiler is free to choose different optimisations (both for space and time), making the code more efficient in the process.
For example, a static storage duration variable (a) is initialised once on program startup and never has to be initialised again.
Marking something as const
allows the compiler to generate more efficient code, knowing full well that the data won't change. As an extreme example, it can load the value into a dedicated CPU register and never look at the data in memory again.
So yes, it can increase performance, not because the same instructions under the covers may run faster, but because the compiler is free to use different instructions based on the extra knowledge you have given it.
(a): Assuming that's the meaning you have of static
. There's a couple of other things that keyword is used for regarding limiting its scope of visibility, which is good programming practice.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With