1,475 views

3 Answers

Best answer
4 votes
4 votes

You have in fact told the answer in question.

int * const ptr = &i;

Why was initialization required here? Because the pointer ptr is a constant and any constant variable must be initialized in C. We can also declare the same as

const * int ptr = &i;

Now, for second one you did not initialize. And that is not required also as const int * ptr or int const * ptr is a pointer to a const int meaning it can point to any integer but we are not supposed to modify the pointed value using '*' operator (trying to modify causes undefined behaviour).

selected by
4 votes
4 votes

Reading backward and stop at $*$ symbol first: then continue:

First case:

This $ptr$ needs initialization because it is a constant.


Second case:

This $ptr$ needs no compulsory initialization.

0 votes
0 votes
Ohhhh

i got it.

first const int * ptr;

means we can not change the the value of *ptr . we can change the ptr means address can change.

Example

#include <stdio.h>

int main ()
{
 int i=8;
 const int *ptr=&i;
 *ptr=9;
 printf("%d",*ptr);
}

second int * const ptr;

means we can not change the address mean we can not change ptr value;

Example

#include <stdio.h>

int main ()
{
 int i=8;
 int * const ptr=&i;
 *ptr=10;
    int j=150;
    ptr=&j;
 printf("%d",*ptr);
}

Related questions

1 votes
1 votes
1 answer
1
_shashi asked Jan 27, 2018
684 views
what is the difference between *b[10] and (*b)[10] ?
0 votes
0 votes
1 answer
2
0 votes
0 votes
1 answer
3
Isha Karn asked Dec 8, 2014
13,159 views
int x=5; void f() { x = x+50; } void g(h()) { int x=10; h(); print(x); } void main() { g(f()); print(x); }1) what is output if code uses deep binding?2)what is the output...