Type Qualifiers in C

There are two types of Qualifiers:

1. Const & 2. Volatile

Syntax:

<type> datatype variable_name;
  • We can use “const” term with primary and secondary datatypes.

Now we will check some cases of usage of ‘type qualifier’ :

1. const int *p;

Here, p is the integer pointer, pointing to a read-only memory location.

2. int *const p;

Here, pointer is constant so we can modify the data.

3. int const *p;

Here, same as first case p is the integer pointer, pointing to a read-only memory location.

4. const int *const p;

Here, pointer is constant and also pointing variable is constant.

For example :

main()
{
     int i = 10;
     const int *p;

     p = &i;
     printf("%d \n",*p);

     *p = *p + 1;
     printf("%d \n",*p);
}

Answer: Here, it will give an error because the pointer is pointing to read-only memory and in *p + 1 we are incrementing by 1. So, that’s not possible in this case. Hence it will give an error.

  • When we deal with a const pointer, it must & should be initialized.

For example :

main()
{
    int i = 10 , j = 20;
    int *const p = &i;
    printf("%d \n",*p);
    *p = *p + 1;
    printf("%d \n",*p);
}

Answer: 10

11

 

 

 

 

 

 

 

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s

Powered by WordPress.com.

Up ↑

%d bloggers like this: