C/C++ String constants

C/C++ String constants are very unique. They will be allocated in global read only memory. One string literal will be allocated only once if we use thousand times also. For example char *a = “samba”; is a string constant, but not these char a[] = “samba”; string a = “samba”; The following are the advantages of string constants 1. We can store only pointer in our datastructure (no need of strdup) for example struct A { int x; char *y; }; A a = {20, “samba”}; 2. We can use pointer comparison than string comparison for example char *a[] = {“samba”, “siva”, “rao”}; for(int i = 0 ; i < sizeof(a)/ sizeof(char*) ; ++i) { if( a[i] == “samba”) // here is pointer comparison //do something } So when there is need for readonly string data, please use string literal


Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s