Skip to content

Instantly share code, notes, and snippets.

@joegasewicz
Last active November 23, 2022 13:25
Show Gist options
  • Save joegasewicz/326e41bcf8ac38513b0ef315984be305 to your computer and use it in GitHub Desktop.
Save joegasewicz/326e41bcf8ac38513b0ef315984be305 to your computer and use it in GitHub Desktop.
C Pointers To Consts
/* ====================================================================== */
/* Pointers & consts */
/* ====================================================================== */
/* POINTERS TO CONSTS */
long value = 9999L;
long value2 = 1111L;
// only the value of what the pointer is pointing to is a constant
// we can still change the reference of what the pointer is pointing to
const long *pvalue = &value;
// *pvalue = 1L; // throws error
value = 1L; // OK
printf("value: %d\n", value);
// change the address of pvalue
pvalue = &value2;
printf("pvalue = %d\n\n\n", *pvalue);
/* CONSTANT POINTERS */
int count = 43;
int count2 = 44;
// after assignment, pcount cannot change the address it points to
int *const pcount = &count;
// pcount = &count2; // throws error
*pcount = count2; // we can change the value
printf("pcount = %d\n", *pcount); // 44
printf("count = %d\n", count); // 44
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment