C - const and static keywords

Ok, once and for all, I'll try to clarify to meaning of the 'const' and 'static' keywords in C (it applies to Objective-C and C++ too).

I'm just tired of questions about this on StackOverflow.

Objective-C programmers usually don't think about C code while coding. I personally think this is a big mistake (it can sometimes apply to C++ programmers too).

Objective-C is just a layer over C. So in order to be a good Objective-C programmer, you HAVE to know at least a few things about the C language.

I don't know why C has such a bad reputation for Objective-C coders, especially on iOS. And it's very surprising to see the lack of knowledge of some Objective-C developers.

So once and for all:

If you want to code in Objective-C, learn at least the following C topics:

  • Language keywords and their meanings
  • Pointers and pointer arithmetic
  • C standard library

Those are the (very) basics.

Objective-C is a very nice object-oriented language, with amazing runtime capabilities. That's true.
But it doesn't mean you can bypass completely the C language.
A lot of time, you'll save a lot of processor time and memory, just by knowing a few things about the C language, rather than relying on the apparent simplicity of the Objective-C language.

But that's a different story. Now back on our keywords...

const

First of all, the const keyword.

Ok, it means 'constant'... So:

const int x = 42;

declares a constant integer variable. It means its value can't be modified. Its value is initially assigned to 42.
If you try to change its value later, the compiler will issue a warning, or an error, depending on your compiler settings.
So the following statement is invalid:

const int x = 42;
x           = 43;

That's pretty easy to understand.
The problem comes with pointers.

Let's take a look at the following code:

char * str = "hello, world";

It declares a char pointer. Ok… But then what about this:

char * const str = "hello, world";

or

const char * str = "hello, world";

Now read carefully.
The first one declares a constant pointer to a char.

It means the the characters of the string can be modified, but not the pointer value.
So the variable str cannot be assigned to another pointer.

For instance, this is invalid:

char * hello     = "hello, universe";
char * const str = "hello, world";
str              = hello;

as your a modifying the pointer value (not the string value).

This is valid:

char * const str = strdup( "hello, world" );
str[ 0 ]         = 'a';

The str variable will then contain aello, world. Remember: the pointer can't be modified, the value that is pointed can be.

It's the exact opposite with the following notation:

const char * str = "hello, world";

Here, you can assign the pointer to another variable, but you can't change the value.

The const keyword is contextual, in a way, when using pointers. It can apply to the pointer itself, or to the value pointed.

So, in order to resume:

const int * x;

A modifiable pointer to a constant integer.

int * const x;

A constant pointer to an modifiable integer.

const int * const x;

A constant pointer to a constant integer.

static

The static keyword can have two meanings.

First of all, it can be declared inside a function.
Let's take a look at this example:

#include <stdio.h>

void foo( void );
void bar( void );

void foo( void )
{
    int x = 0;
    
    printf( "X - foo: %i\n", x );
    
    x++;
}

void bar( void )
{
    static int x = 0;
    
    printf( "X - bar: %i\n", x );
    
    x++;
}

int main( void )
{
    foo();
    foo();
    foo();
    bar();
    bar();
    bar();
    
    return 0;
}

The output will be:

X - foo: 0
X - foo: 0
X - foo: 0
X - bar: 0
X - bar: 1
X - bar: 2

Because a simple local variable, as in the foo function, only exists when the function is called. It's destroyed (to be simple) when the function exits.

So for the foo function, the variable is created each time the function is called, with a value of 0. The value is printed, then incremented.
The function then exit, and the variable is destroyed.

But in the bar function, the variable is declared as static. It means the value will persist across function calls.
It's initialized the first time the function is called, but only at that time. Once it has been initialized, it just exist, so its value will be taken for the next function calls.

Now the static keyword as a completely different meaning when used in a variable declared outside of a function (in the global scope).

It means that the variable will be «file scoped». In other words, the variable, which is global, will be accessible only from the scope of the file which declared it. It won't be accessible from other files.

It's just a way to create global private variable.

For instance, imagine a file called foo.c:

int        x = 42;
static int y = 42;

From a bar.c file, you'll be able to access the x symbol, if both files are linked together. But you won't be able to access the y symbol, as it's decaled as static.
It means that the symbol for the y variable won't be exported by the linker, when the symbol for the x variable will be.

In other words, you'll be able to access the y global variable only from function declared in the foo.c file. The x variable will be also accessible from other files.

Of course, the static keyword can be combined with const.
For instance:

static const int * const y;

A constant pointer to a constant integer, that will be accessible only from the file which declared it.

Comments

Author
Pieter
Date
11/13/2011 14:07
You wrote:

"char const * str = "hello, world"; 

Now read carefully.
The first one declares a constant pointer to a char."
This statement is not true. 
For a constant pointer, the const needs to be after the star.
Author
Jean-David Gadina
Date
11/13/2011 15:35
Sorry for the typo : ) Corrected.
Author
Aman
Date
06/19/2012 13:59
awesome explaination of the two different meanings of the static keyword.
could u also explain me the meanin of volatile keyword with example. pls send me the explanation thru mail
Author
DHARMATHEJA
Date
07/12/2012 11:00
Really good....and easy to understand.
Thank you so much for explaining clearly.
Author
Sunil M M
Date
08/06/2012 08:24
nice explanation of static and const key words
Author
Srishti
Date
08/07/2012 05:43
Thanks to you, iv finally understood how to use "const"!!
Author
Kurma Reddy M
Date
08/29/2012 17:32
Excellent explaination about const and static.
I really appreciate if you can explain about "volatile" usage
Thanks in advance
Author
joao
Date
09/26/2012 11:13
Great!
Author
Josh
Date
12/11/2012 03:17
As someone who's been doing Obj-C for a 1.5+ yrs and occasionally had to research these concepts to brush up, this has been the best guide I've come across, so far. Thanks for posting this!
Author
vikram
Date
04/11/2013 10:34
It's nice ..very easily understandable . can you explain the pointer concept similarly , like function pointer ,memory managment with pointer.
Author
Gatikrushna
Date
04/27/2013 15:48
great explanation
Author
C: const and static keywords | stackoverflow1453
Date
06/25/2013 13:55
[...] Source: http://www.noxeos.com/2011/07/29/c-const-static-keywords/ [...]
Author
Reeganth
Date
06/26/2013 04:52
Great :) thk u..
Author
Ankie
Date
07/21/2013 06:36
Nice and clear....
Author
Annonie
Date
08/10/2013 13:49
Great explanation....
Can u please tell me if at all static and extern can be used together...
Author
Jean-David Gadina
Date
08/11/2013 19:18
With static, you tell the compiler that your symbol can be visible only in your compilation unit (source file). So combining with extern is a non-sense.
Author
julian
Date
09/18/2013 11:16
Thanks.
Author
iqra nawaz
Date
10/31/2013 00:41
v good explanation thanku so much :)
Author
minator
Date
12/16/2013 10:41
can i do something like: const int * static const y;
which could mean static constant pointer to a constant integer?
if it was valid, could you plz explain the scope of y?
Author
parth
Date
01/29/2014 14:31
Slightly disappointed to note that you have not mentioned the third use of the static keyword - for creating static functions. For completeness, it would be nice if you included an example or at least mentioned it in passing.
Author
Ido
Date
05/07/2014 12:37
Explanation was very good.
I now understand the meaning of commands const & static.
I tried the example given and it's work.
But still i do not understood one thing: If static acting as a const in the main program , how you can change the value of static in the function?
Author
Anand Parshuramka
Date
09/08/2014 11:21
Excellent :)
Author
Khushalee
Date
09/27/2014 05:19
Nice explnation of Static keyword.
Thnx a lot.
Author
Nice Work
Date
09/28/2014 01:46
Great work explaining. Thank you!

Add a comment