Sanfer
Sanfer

Reputation: 413

Constants in C: declaration separate from definition

All C code:

Why is this allowed:

int main()
{
    const int *i;
    int j=2;

    i=&j;
}

But not this:

int main()
{
    const int i;
    int j=2;

    i=j;
}

Is there a way to declare a local constant variable and then define it elsewhere within the scope? The first case that uses a pointer is unreliable because I can get away with defining it multiple times, defeating the purpose of the constant keyword in the first place.

Upvotes: 1

Views: 1001

Answers (2)

new299
new299

Reputation: 814

Semantically the first example means "a pointer to a const int" not "a const pointer to an int".

So, when you set i to point to j (a non-const int). i now points to a const, as such you can't change the value of j through the pointer i, for example:

int main()
{
    const int *i;
    int j=2;

    i=&j;

    *i = 4;
}

Won't compile, giving the error "assignment of read-only location ‘*i’". So the pointer restricts your access to the value being pointed to. But the pointer itself can still be changed.

C being the language that it is, doesn't really offer much protection and you can often throw away the const and assign the variable a new value anyway e.g.:

#include <stdio.h>

void assign(int *a) {
  *a=5;
}

int main()
{
    int const i=1;
    int j=2;
    assign((int *) &i);
    printf("i: %d\n",i);
}

But I'm not sure I'd recommend it. And while this works in some versions of gcc, this behavior is likely undefined in the C standard.

Upvotes: 1

CIsForCookies
CIsForCookies

Reputation: 12817

const int *i means that the int pointed to by i is const, so you can't do *i = j. But const int i means i itself is const so you must declare it like const int i = 2; and then it remains const and can't be touched.

The difference is what you change. If you have a const integer - it can't be changed, if you have a pointer to const integer - and the pointer is not const, well, that pointer can be assigned to point to whatever int you would like.

To answer your question: no, you can't define a const int and then redefine it. That negates the meaning of const.

Upvotes: 1

Related Questions