0

Anyone can explain me what is the difference between two blocks of code below:

func1 (...)
{
    int32_t index;
    const int32_t *p;
    p =& (index);
}
func2 (...)
{
     const int32_t s;
     s=10;  
}

It is possible to declare a const pointer and then assign a value to it but it is not possible to declare a normal variable and then assign a value to it. Can somebody explain this to me?

I get a pc-lint error that I have to declare the const variable inside the function but I cannot do it. How can I get rid of this error?

Thank you so much.

Mat
  • 202,337
  • 40
  • 393
  • 406
sara
  • 7
  • 1
  • You can add "number_of_stars + 1" `const` to a declaration; the `const` applies to whatever is on its immediate right: `int [const] * [const] * ... [const] foo = value;` – pmg Aug 29 '20 at 08:22
  • `const int32_t s; s = 10;` compiler error ... `int32_t * const p; p = NULL;` compiler error – pmg Aug 29 '20 at 08:25

3 Answers3

3

That's because they're not doing the same thing (using T as type since I'm basically lazy):

const T *p; // non-const pointer to const T.
const T s;  // const T.

It may help to think of the former as binding like [const T] [*p].

If you want a const pointer, you do that with one of:

T * const p;         // const pointer to non-const T, [T*] [const p]
const T * const p;   // const pointer to const T, [const T*] [const p].
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
1
int i=0;
const int *p=&i;
*p = 10; /*error*/

This is incorrect, because p is declared pointer to constant int, so you cannot change the integer value p points to, via p.

int i=0;
int const *p=&i;
*p = 10; /* i will be 10 */

This is correct, because p is declared constant pointer to int, so you can change the integer value p points to, via p.

int i=0;
const int const *p;
p = &i;  /*error*/
*p = 10; /*error*/

This is incorrect, because p is declared constant pointer to constant int, so you cannot change neither the integer value p points to, via p, nor the value of p after it's declared.

alinsoar
  • 15,386
  • 4
  • 57
  • 74
0

"It is possible to declare a const pointer and then assign a value to it..."

const int32_t *p is not a const pointer to int32_t. It is a non-const pointer to const int32_t.

int32_t * const p; would give you a const pointer to int32_t. Take care of that the const specifier is at the right side of the * declarator.

You can modify the pointer itself however you want because it is not const, so p = &(index); is fine. Note that the parenthesis are redundant.

"...but it is not possible to declare a normal variable and then assign a value to it."

const int32_t s; is not a "normal modifiable" variable. It is declared with const. You cannot assign a const variable after its definition/initialization. You can only initialize it once at its definition.

Thus, using

 const int32_t s;
 s = 10; 

gives you of course an error.

How can I get rid of this error?

Initialize s at its definition:

const int32_t s = 10;