Output of the Program | Pointer to a Constant or Constant Pointer?
Predict the output of the below program.
int main() { int x = 5; int * const ptr = &x; ++(*ptr); printf("%d", x); getchar(); return 0; } |
chevron_right
filter_none
Output: 6
Explananation:
See following declarations to know the difference between constant pointer and a pointer to a constant.
int * const ptr —> ptr is constant pointer. You can change the value at the location pointed by pointer p, but you can not change p to point to other location.
int const * ptr —> ptr is a pointer to a constant. You can change ptr to point other variable. But you cannot change the value pointed by ptr.
Therefore above program works well because we have a constant pointer and we are not changing ptr to point to any other location. We are only icrementing value pointed by ptr.
Try below program, you will get compiler error.
int main() { int x = 5; int const * ptr = &x; ++(*ptr); printf("%d", x); getchar(); return 0; } |
chevron_right
filter_none
Recommended Posts:
- Output of C++ Program | Set 19
- Output of C++ Program | Set 20
- Output of C Program | Set 29
- Output of C++ Program | Set 11
- Output of C++ Program | Set 9
- Output of C++ Program | Set 8
- Output of C Program | Set 28
- Output of C Program | Set 26
- Output of C program | Set 25
- Output of C++ Program | Set 1
- Output of C++ Program | Set 3
- Output of C++ Program | Set 10
- Output of C Program | Set 18
- Output of C++ Program | Set 5
- Output of C++ Program | Set 4



