Select Page

You have two options when you deal with characters in C++: char or string. They may look somewhat similar at first glance, but they serve radically different purposes.

As an aspiring developer, you may not know when to use char over string, or what their exact purposes are. What is its purpose exactly? In this article, we will focus on how char works in C++ and when you should use it instead of string. Our practical examples will show you how to best use the char and string types. Let’s dive in! 

What Is Char in C++?

Computers only deal with numbers and do not understand characters as such. But as humans, we like to read and write using the characters of our respective languages. That’s why a character type is integrated into programming languages like C++.

char allows you to store individual characters or arrays of characters and manipulate them. But how does it all work? What are best practices for dealing with char in C++? We’ll now address these questions. 

Simple Example of Char in C++

In the memory, char is stored as an integer representing the ASCII value of the character. For example, if we were to store the value of a school grade in a char variable, we would use this syntax:

#include <iostream>
using namespace std;
int main()
{
// Declaring  a char variable for storing a school grade
char mathGrade = 'A';

// Displaying the grade in a sentence
      cout << "Congratulations! You scored an " << MathGrade << " at your last exam!" << endl;
}

Running this program displays a sentence containing the value of the variable mathGrade.

Congratulations! You scored an A at your last exam!

Now if we wanted to find out the ASCII value of a given character, we would use the following code:

#include <iostream>
using namespace std;
int main()
{
// declaring  a char variable for storing a school grade
char mathGrade = 'A';

// Displaying the grade as an ASCII value
      cout << "The ASCII value of this grade is " << int(MathGrade) ;
}

In this example, we used the letter “A.” The ASCII table tells us that the decimal value for “A” is 65 (when viewed as an integer). Therefore, the output of the program is as follows: 

The ASCII value of this grade is 65

But what if you needed to store more than a single character using char? There’s a solution for that, and it’s the char array.

What Are Char Arrays?

In C++, you can create and use arrays of elements of the same type. An array is a collection of elements of the same type that can be referenced individually using an identifier. The image below shows you how arrays work, the example being a char array. If you want to know more about arrays, check out our article on the topic.

In this example, we use an array of char to store the letter grades used at most U.S. high schools. If we wanted to assign a grade to a student based on their performance, and then display it, we would use the following bit of code:

#include <stdio.h>
#include <iostream>
using namespace std;

int main()
{
    // Declaring 2 variables to store the grades and the student results
    char publicHighSchoolGrades[5] = {'A', 'B', 'C', 'D', 'F'};
    int studentResult;
    int gradeIndex;
     
    // Ask the user to input the student's test result
    cout << "Please enter the student's result: ";
    cin >> studentResult;
     
    // Use a switch statement to display the right grade
    switch (studentResult) {
        case 90 ... 100:
          gradeIndex = 0;
          break;
        case 80 ... 89:
          gradeIndex = 1;
          break;
        case 70 ... 79:
          gradeIndex = 2;
          break;
        case 60 ... 69:
          gradeIndex = 3;
          break;
        case 0 ... 59:
          gradeIndex = 4;
          break;
    }
    cout << "The student's score is: " <<
        publicHighSchoolGrades[gradeIndex] << endl;
}

The console displays the following output : 

Please enter the student's result: 88
The student's score is: B

When Should I Use Char?

Since the keyword string doesn’t exist in C, char arrays are the only way to store words or sentences in the language. Yet in C++, string is sometimes more convenient to use because the C++ string library provides many functions to operate directly on strings. For example, you can search for strings or subdivide them into substrings. But char remains extremely useful when characters have a different role, such as for grades (as you can see in our above example), special notation, algebra, and so forth. 

Let’s now create a program to gather students’ responses to a multiple-choice exam question. The use of char is relevant here. It’s both memory-efficient and simple to use: 

#include <iostream>#include <stdio.h>
using namespace std;

int main()
{
// Declaring the char variables to store the student’s answer
char StudentAnswer;

// Get the students answer
cout << "What is the capital of Switzerland ?" << endl << "A - Bern \n" << "B - Zurich \n" << "C - Geneva \n";
cout << "Type your answer here and press Enter: ";
cin >> StudentAnswer;

//Compare the Student's answer with the correct answer and provide feedback
if (StudentAnswer == 'A' || StudentAnswer == 'a') {
    cout << "Congratulations ! You got the right answer !";
} else {
    cout << "Sorry. The capital of Switzerland is Bern";
    }
}

Here’s what the output looks like:

What is the capital of Switzerland?
A - Bern
B - Zurich
C - Geneva
Type your answer here and press Enter: A
Congratulations! You got the right answer!

char arrays are also preferred to string when it comes to performance, especially on embedded devices. Say we’re coding an app on a microcontroller in which the user has to type a short passcode to access the interface.

Microcontrollers are much weaker in terms of performance compared to our phones or computers and their memory is very limited. Because string is more complex than char, using the former will will require more resources and therefore more time. Using char arrays solves this problem:

#include <iostream>
#include <stdio.h>
using namespace std;

int main(){
//Declaring variables to store the password and user input
char SystemPass[5] = {'T','P','A','N'};
char UserInput[5];
   
//Asking the user to enter the password
cout << "Please enter the password \n";
cin >> UserInput;
   
for (int i = 0; i < 4; ++i) {
    if (SystemPass[i]!=UserInput[i]) {
    cout << "This is the wrong password";
    return 0;
    }
}
cout << "Great, this is the right password !";
}

If the user types in the right password, the result is:

Please enter the passwordTPANGreat, this is the right password !

Note that when an array is used as a string, the last character is a null value represented by \0. This value does not have to be manually specified, but an array of 9 characters is, in fact, 10 characters long.

When Should I Not Use Char?

In C++, you benefit from the extended functionality of the string object if you need to store longer bits of text. string is somewhat special as it’s not a built-in type of the language. 


Modern compilers have string integrated into their standard libraries, and you can use string as if it were a native type. String works like an optimized char array, and it’s simpler and faster for you to use string rather than char arrays to store words or sentences.

If you’re not concerned with memory management use string instead. We further do not recommend char if you’re handling a large amount of text, or if the size of the text can often vary. From the below example, you’ll see that under certain circumstances, using string is just simpler:

#include <iostream>
using namespace std;

int main()
{
// declaring a char array and assigning a sentence to it
char LongChar[17] = {'J','o','h','n',' ','s','c','o','r','e','d',' ','a','n',' ','A','\0'};

// declaring a string variable and assigning a sentence to it
string LongString = "John scored an A";

// Displaying the result in the terminal
cout << LongChar << "\n";
cout << LongString << endl;
}

Both cout statements display the same result, but it was easier to obtain with string than with char.

John scored an A
John scored an A

Master Char in C++ and Much More

The char data type is both fundamental and indispensable to C++. In this article, we covered how to use char simply and efficiently. We have seen that the use of char helps you resolve specific problems such as memory management in situations where performance is limited. However, using char can be more complicated than string in some contexts, where string will be preferred.

With a solid knowledge of C++, you can start building powerful programs in fields like gaming and healthcare. Our expert-designed C++ Nanodegree can be your first step towards a career as a C++ developer.

Enroll in our C++ Nanodegree program today.