Alex Rivera | Logout

Can we change the value of an object defined with const through pointers?

Asked 2010-09-27T06:30:15.613
32
#include <stdio.h>
int main()
{
    const int a = 12;
    int *p;
    p = &a;
    *p = 70;
}

Will it work?

Edit
Report

2 Answers

6

It does indeed work with gcc. It didn't like it though:

test.c:6: warning: assignment discards qualifiers from pointer target type

But the value did change when executed. I won't point out the obvious no-no...

answered 2010-09-27T06:36:28.423
0

You cannot change the value of a constant variable by using a pointer pointing to it. This type of pointer is called as Pointer to a constant.

There is also another concept called Constant Pointer. It means that once a pointer points to a memory location you cannot make it point to the another location.

answered 2010-09-27T06:41:12.253

Your Answer