I see it everywhere:
- http://www.cplusplus.com/reference/cstdio/printf/ -> printf takes format as
const char *fmt
rather thanchar * const fmt
. - https://msdn.microsoft.com/en-us/library/e0z9k731.aspx -> strings accepted as const pointers rather than pointer consts.
- glShaderSource: https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glShaderSource.xhtml -> strings taken as const pointer rather than pointer const.
- https://msdn.microsoft.com/en-us/library/windows/desktop/ms645505(v=vs.85).aspx -> messageboxa/messageboxw take const pointer to string rather than pointer to const.
Am I misunderstanding something, or is this just misunderstanding on how to express things in C by api designers?
From my understanding,
const char *a
, is a pointer to a char which you cannot change to point to another char.char * const a
is a pointer to a char which you cannot dereference to change value of.const char * const
a is a pointer to a char which you cannot change to point to another char(or the first char of contiguous block containing many chars), AND you cannot change the value of the pointed char by dereference.
Thanks ahead of time.
It appears I got it other way around:
char *elephant = "elephant";
const char *p1 = "wolf";
char * const p2 = "sheep";
int main(int argc, char **argv)
{
p1 = elephant;
*p1 = elephant[0]; /* error: assignment of read-only location '*p1' */
p2 = elephant; /* error: assignment of read-only variable 'p2' */
*p2 = elephant[0];
return 0;
}
analogous:
#define ptrto(X) X *
#define readonly(X) X const
char const a = 'a';
const char b = 'b';
readonly(ptrto(char)) p1 = "p1";
ptrto(readonly(char)) p2 = "p2";
int main(int argc, char **argv)
{
p1 = &a; /* error: assignment of read-only variable 'p1' */
*p1 = a;
p2 = &a;
*p2 = a; /* error: assignment of read-only location '*p2' */
p1 = &b; /* error: assignment of read-only variable 'p1' */
*p1 = b;
p2 = &b;
*p2 = b; /* error: assignment of read-only location '*p2' */
return 0;
}