What is the difference between char, const char, char const, const char const :

we planned to write some useful  information. I am working as a C, C++ developer. So I want to share some useful information regards my own domain.

 

Now  I am going to differentiate,

char *szVar

const char *szVar;

char const *szVar;

const char * const szVar;

 

char *szVar=”char”   – Here we can change value and address of the variable.

const char *szVar=”char” – Here we can change of the value is possible but change of the address is not valid . compiler tells this is as the error.

char const *szVar=”char” – Here we change of the address is possible but change in the value is not possible. which means,

szVar = “hello”   -> It points another address , so this is valid.

strcpy(szVar,”hello”) – > It is not possible.

const char const szVar =”char”  – Here change of address and value is not possible. Please refer the below program and let me know if there is any bugs. Thanks in advance.

 

 

/*
* Description : Illustration of difference between different type of illustration
*
* Note : Best viewed in VIM editor
*
*/

#include<stdio.h>
#include<string.h>

int main(){

// change in both the value and the content at the address are valid
char *szVar=”char”;

// change in the value of the variable is valid
// change in the content at the address in the variable is not valid
const char *szVar1=”const char”;

// change in the value of the variable is not valid
// change in the content at the address in the variable is valid but will cause Segmentation Fault
char const *szVar2=”char const”;

// change of both value and content at the the address is invalid
const char * const szVar3=”const char const”;

szVar=”New Value”; // valid statement
strcpy(szVar, “New Value”); // valid statement but will cause segmentation fault

szVar1=”New Value”; // valid statement
strcpy(szVar1, “New Value”); // compiler error

szVar2=”New Value”; // compiler error
strcpy(szVar2, “New Value”); // valid statement but will cause segmentation falut

szVar3=”New Value”; // compiler error
strcpy(szVar3, “New Value”); // compiler error

return 0; }