C Programming - Const - Discussion

Discussion Forum : Const - Find Output of Program (Q.No. 4)
4.
What will be the output of the program?
#include<stdio.h>

int main()
{
    const int x=5;
    const int *ptrx;
    ptrx = &x;
    *ptrx = 10;
    printf("%d\n", x);
    return 0;
}
5
10
Error
Garbage value
Answer: Option
Explanation:

Step 1: const int x=5; The constant variable x is declared as an integer data type and initialized with value '5'.

Step 2: const int *ptrx; The constant variable ptrx is declared as an integer pointer.

Step 3: ptrx = &x; The address of the constant variable x is assigned to integer pointer variable ptrx.

Step 4: *ptrx = 10; Here we are indirectly trying to change the value of the constant vaiable x. This will result in an error.

To change the value of const variable x we have to use *(int *)&x = 10;

Discussion:
18 comments Page 1 of 2.

Nihaal said:   7 months ago
Here Const int x = 5 means the x variable is const we cannot change ok.

Also, const int *p means the pointer pointing to a variable is also constant. (so in line number 3, p = &x,

So, now it means a pointer pointing to a constant value which is also defined as constant )

const int*p ---->>> const *p (means it is pointing to a constant value, so we cannot change it.)

If you remove const int x = 5 ------>>>>int x =5, then also it gives an error bcoz this statement const int *p means it is pointing to a constant value simple.

So you cannot change it.
(1)

Rajlaxmi said:   2 years ago
const int *ptrx -> Pointer to the constant integer.So we can't modify the value present at ptrx.

However if we want to modify then type casting will help. That is *(int *)ptrx = 10; or *(int *)&x = 10.

Haritha said:   2 years ago
*(int *)&x = 10;

Please explain this.

Gaurav said:   5 years ago
*(int *)&x = 10;
Please explain this.

Suresh said:   6 years ago
Why cannot print x values of 5?

Abhayraj SN said:   7 years ago
The variable "x" of integer data type is declared as constant with assigning value 5.

ptrx is a pointer to the integer data type. Means, it stores integer values only.

You may correct or suggest me.

Rishi said:   7 years ago
What is const int x=5;int *ptrx;?

Please explain.

Emerson said:   8 years ago
Hi Shiva,

I think,

If const variable will be located in Read Only section of the memory. Trying to modify it will result in runtime error. Signal will be sent to the process in Linux.

Shiva kumar said:   9 years ago
Using pointers we can change any kind it of data.

Even if it is constant variable also. That is why there is no security in C.

Hotcpu said:   9 years ago
This is an undefined behavior by casting away the const definition. However, it will not work in g++ 4.1+.


Post your comments here:

Your comments will be displayed after verification.