Q:

Differentiate between a constant pointer and pointer to a constant?

0

Differentiate between a constant pointer and pointer to a constant?

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Answer:

Constant pointer:

A constant pointer is a pointer whose value (pointed address) is not modifiable. If you will try to modify the pointer value, you will get the compiler error.

A constant pointer is declared as follows :

Data_Type * const Pointer_Name;
eg,
int *const ptr; //constant pointer to integer

Let’s see the below example code when you will compile the below code to get the compiler error.

#include<stdio.h>
int main(void)
{
    int var1 = 10, var2 = 20;
    //Initialize the pointer
    int *const ptr = &var1;
    //Try to modify the pointer value
    ptr = &var2;
    printf("%d\n", *ptr);
    return 0;
}

Pointer to a constant:

In this scenario the value of the pointed address is constant that means we can not change the value of the address that is pointed by the pointer.

A constant pointer is declared as follows :

Data_Type  const*  Pointer_Name;
eg,
int const *ptr// pointer to const integer

Let’s take a small code to illustrate a pointer to a constant:

#include<stdio.h>
int main(void)
{
    int var1 = 100;
    // pointer to constant integer
    const int* ptr = &var1;
    
    //try to modify the value of pointed address
    *ptr = 10;
    
    printf("%d\n", *ptr);
    return 0;
}

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
What are the post-increment and decrement operator... >>
<< What is the output of the below C program?...