697 views
1 votes
1 votes
#include<stdio.h>
int main()
{
    int x=3;
    int const *ptr =&x;
    printf("%d",++x);
    printf("\n %d",++*ptr);
    return 0;
}



 

I am unable to get that when x is a variable not a constant then how come the error is that the since ptr is a pointer to a constant hence we cannot change its value, although ++x works fine, whats the logic behind this ?

2 Answers

Best answer
1 votes
1 votes
Type of ptr is pointer to const int, hence it is an error for compiler if we try to change the value it is pointing to.
selected by
2 votes
2 votes
We must value the type of any data type.

$x$ is an integer and hence we can always modify it.

$ptr$ is a pointer to a constant integer and hence we are not supposed to modify the pointed to value of $ptr$. This is particularly useful when passing a pointer to a function and we want to ensure no modification to the pointed value happens.

Related questions

0 votes
0 votes
1 answer
1
radha gogia asked Feb 23, 2016
564 views
when constant type variables cannot be modified then why do we consider them as lvalues , why not only r-values ?
0 votes
0 votes
1 answer
4