why does this happen with const pointer to int?

I wrote the following two codes. but one is giving erro


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
  #include <iostream>

using namespace std;

int main()
{
    int var1=10;
    int *const ptr;
    ptrt=&var1;


    cout<<*ptr;

    return 0;
}


why does the above code is giving error?
and the same code with minor difference is running fine?
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>

using namespace std;

int main()
{
    int var1=10;
    int *const ptr=&var1;
    
    cout<<*ptr;

    return 0;
}

is it always necessary to initialize the const pointer to int at the declaration itself ??


Last edited on
is it always necessary to initialize the const pointer to int at the declaration itself ??

Basically, yes. However, note the differences between
int const*, int *const, and int const* const:
Which respectively denote
- an integer-constant pointer (i.e., a pointer to integer-constant)
- an integer pointer-constant (i.e., a constant pointer to integer)
- an integer-constant pointer-constant (i.e., a constant pointer to integer-constant).

given int* const, it is the pointer which is constant, not the pointed-to integer.
Last edited on
can you tell me where can anybody use this int * const??

I mean, I wanted to know the practical use of this method..

Thanks in advance

can you tell me where can anybody use this int * const??

Any time you don;t want a pointer changed.

A common use of this is when specifying a pointer as an argument to a function. Since a pointer is passed by value, changing the local copy of the pointer is usually a logic error. Declaring the pointer argument as const prevents this.

Topic archived. No new replies allowed.