Wednesday 2 January 2013

C/C++ Puzzles: PART - 15

Pointers and Constants

Consider the two declarations given below.
const char *str1;
char const *str2;
Both the declarations are same and tells the compiler that the pointers point to a constant string. But the pointers themselves are not constant.

Now consider the declaration given below.
char *const str3;
Here the pointer is a constant but the string pointed by the pointer is not a constant.

Now consider the declaration given below.
const char *const str4;
Here both the pointer and the string the pointed by the pointer are constants.

The program given below shows the difference between the above mentioned pointers.

#include<stdio.h>
int main()
{
     char const *str1="Hello";
     const char *str2="Hello";
     char *const str3="Battle";
     const char *const str4="Battle";
     printf("\nstr1 is %s",str1);
     //*str1='h'; //This Statement will give you an Error.
     str1="Hai";  // This Statement works fine.
     printf("\nNow str1 is %s",str1);
     printf("\nstr2 is %s",str2);
     //*str2='h'; //This Statement will give you an Error.
     str2="Hai";  // This Statement works fine.
     printf("\nNow str2 is %s",str2);
     printf("\nstr3 is %s",str3);
     //str3="Cattle"; //This Statement will give you an Error.
     *str3='C';  // This Statement works fine.
     printf("\nNow str2 is %s",str3);
     printf("\nstr4 is %s\n\n",str4);
     //*str4='C'; //This Statement will give you an Error.
     //str4="Cattle"; //This Statement will also give you an Error.
     return 0;
}



Download.

Figure Below Shows the Output

No comments:

Post a Comment