Thursday, 25 January 2018

Whats the difference between const char* and char* const ?

·       const char*
is a mutable pointer to an immutable character/string. You cannot change the contents of the location(s) this pointer points to. Also, compilers are required to give error messages when you try to do so. For the same reason, conversion from const char * to char* is deprecated.

·       char* const
is an immutable pointer (it cannot point to any other location) but the contents of location at which it points are mutable.

·       const char* const
is an immutable pointer to an immutable character/string



#include <string.h>
int main()
{
    char *str1 = "string Literal";
    const char *str2 = "string Literal";
    char source[] = "Sample string";

    strcpy(str1,source);    //No warning or error, just Undefined Behavior
    strcpy(str2,source);    //Compiler issues a warning

    return 0;
}


No comments:

Post a Comment