w3resource

Difference between const int*, const int * const, and int const * in C?

C - const int*, const int * const, and int const *?

  • int* ptr1 – ptr1 is a pointer to int
  • int const * ptr2 - ptr2 is a pointer to const int
  • int * const ptr3 - ptr3 is a const pointer to int
  • int const * const ptr4 - ptr4 is a const pointer to const int
    Now the first const can be on either side of the type so:
  • const int * ptr1 == int const * ptr1
  • const int * const ptr2 == int const * const ptr2
    You can do things like this:
  • int ** ptr1 - ptr1 is a pointer to pointer to int
  • int ** const ptr2 - ptr2 is a const pointer to a pointer to an int
  • int * const * ptr3 - ptr3 is a pointer to a const pointer to an int
  • int const ** ptr4 - ptr4 is a pointer to a pointer to a const int
  • int * const * const ptr5 - ptr5 is a const pointer to a const pointer to an int

Example: Pointer to Constant

#include <stdio.h>
int main() 
{
  const int x = 10;
  const int y = 20;
  const int *z = &x; /* z is a "pointer to a constant." */
  x = 30; /* Error. Cannot change x. */
  y = 40; /* Error. Cannot change y. */
  z = &y; /* OK. */
 *z = 50; /* Error. Cannot change *z */
  return 0;
}

Example: Constant Pointer:

#include <stdio.h>
int main() {
int x = 10;
int y = 20;
int *const z = &x; /* z is a "constant pointer." */
x = 30; /* OK. */
y = 40; /* OK. */
z = &y; /* Error. Cannot change z. */
*z = 500; /* OK. */ 
return 0;
}

Example: Constant Pointer to Constant

#include <stdio.h>
int main() 
{
  const int x = 10;
  const int y = 20;
  const int *const z = &x; /* z is a "constant pointer to a constant." */
  x = 30; /* Error. Cannot change x. */
  y = 40; /* Error. Cannot change y. */
  z = &iSecond; /* Error. Cannot change z. */
 *z = 50; /* Error. Cannot change *z. */ 
  return 0;
}

Contribute your code and comments through Disqus.



Share this Tutorial / Exercise on : Facebook and Twitter

C Programming: Tips of the Day

What's an object file in C?

An object file is the real output from the compilation phase. It's mostly machine code, but has info that allows a linker to see what symbols are in it as well as symbols it requires in order to work. (For reference, "symbols" are basically names of global objects, functions, etc.)

A linker takes all these object files and combines them to form one executable (assuming that it can, i.e.: that there aren't any duplicate or undefined symbols). A lot of compilers will do this for you (read: they run the linker on their own) if you don't tell them to "just compile" using command-line options. (-c is a common "just compile; don't link" option.)

Ref : https://bit.ly/3CbzF8M