Char and Strings similar?

Are they similar? They both can store words, and is it that char variables can store up 256 characters the only difference?
A char is 'a'. You could create a char array to store words for example. string is a built in class from the standard library which basically makes the use of strings easier. There are functions for strings for searching, merging, replacing etc.

Someone else can probably explain it better than I did, but that's the jist of it.
In beginner's point of view, a char data type is used to represent one single character (as it represents the smallest data type). If by "words" you meant a string of characters i.e "word", "program", etc. then these cannot be stored in a char data type. They will be stored in the following ways:
1. (In C and C++) Using an array. For example, the string "word" can be declared as
char c_str[5] = "word";
Keep in mind that an array of char is not the same as a single char data type. You may have seen something like:
char* c_ptr = "word";
this is essentially still an array of char, but it is commonly referred to as C-style strings, or a pointer to char data type if you prefer. Again, this is not the same as char data type. (Note: many texts/people also call array of char data types as C-style strings -pointers and arrays can be used interchangeably, but they are not the same. See other references for details).

2. (Only in C++) Using the std::string class. As mentioned, this class makes it simpler to deal with strings. It wraps around a contiguous char data. It also provides ways to easily manipulate strings. See this reference for details: http://www.cplusplus.com/reference/string/string/

The statement:
char variables can store up 256 characters
is not quite correct. A char data type (by standards and convention) can store up to 28(256) possible values. To have 2 characters in one data type, you will need something other than the char data type.
char* c_ptr = "word";

This is actually a string literal and should be written:
const char* c_ptr = "word";

Note that this code causes a crash (for me at least)
1
2
3
4
5
6
7
8
9
#include <iostream>

int main ()
{
  char *word = "hello\n";
  word[0] = 'H';
  std::cout << word;
  return 0;
}
Last edited on
The idea is that one cannot represent a string of characters using the char data type - string literal or not. But it being a string literal is good to point out for beginners. It's good practice to point out which of your data are supposed to be read only.

Keep in mind though that even if the data type is declared as const, it is not a fool proof solution. One can still deliberately modify a string literal even if it is declared as const char*.
Topic archived. No new replies allowed.