C++ difference between string and char data type

Here let us discuss some of the common differences between ‘char’ and string type.We know that a char type variable can hold only single character but a string type can hold multiple characters(which is also one of the differences between them) but what about their assignment system or some other unobvious behavior which they might exhibit,we will see some of them here.

Link :C and C++ string data type

i)To assign a value to a char variable a single quotation ” is used.But in case of string a double quotation “” is used.

 char c=’B’ ;
string str=”Happy string!” ;

cout<< c << ” ” << str ;

There is no specific reason as to why a char literal is represented under single quotation and string literal under double quotation.The best reason can be they are made to do so.Another reason is language heredity.Since C was using this syntax and C++ was made from C so C++ too went with this syntax.

ii) A char type value can be assigned to string variable but the vice versa is not true.This behavior is reasonable since char consist of only one value converting to string type which can hold many character value is not problematic.

But if we look at the vice versa process converting many characters to a single char is just outrageous,I mean which is the lucky character among many characters in a string that must be chosen to assign to the char variable;it wouldn’t make any sense.So it is not allowed.

unsigned char c=’c’ , c1 ;
string str , str1="Name:" ;
str=c ;

/*c1=str1 ; Error!! */

cout<< str << ” ” << c ;


c c

iii)We can add two strings (with + sign ) and assign the resultant to string and also we can add two characters and assign the resultant to a char variable but,they will yield a different output.

unsigned char c=’3′ , c1 ;
string str , str1 ;

str=c+c ;
str1=str+str ;
c1=c+c ;

cout<< str << endl
  << str1 << endl
  << c << endl
  << c1 ;



For str and c1 two characters are added so in performing c+c their corresponding integer value are added which means c+c is same as 51+51(=102) and the resultant value is assigned to the variable str and c1.And since 102 value correspond to the character ‘f’ in ASCII chart we got the output ‘f’. But for str1 two strings are added,in such case the second value will be concatenated to the first value so str+str(“3″+”3”) gives “33“.

Leave a Reply

Your email address will not be published. Required fields are marked *