1. When passing a string as input, add const in general
For example:
int strlen(const char * str);Here, the string str does not need to be modified inside this function, so it can be qualified with const.
This way, when we call strlen, we can write:
strlen("abc");Without const, a warning will show up:
Note the difference:
char *strcpy(char *dest,const char *src); The first parameter is for output, and the second is for input.
You can pass data directly as an input parameter, but an output parameter requires a pre-allocated buffer:
C
char dest[200];
strcpy(dest,"abc");Only then will it work.
2. const means the object it qualifies is read-only
C
#include <stdio.h>
int main()
{
const char *p = "abc";
char str[]="def";
p = str;
printf("%s",p);
return 0;
}What is the result when you compile and run it?
The answer:
No errors; it prints def.
After being qualified with const, the memory that p points to is read-only, but the value of p itself can still change.
Comments
No comments yet — be the first to write one.