
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What do single quotes do in C++ when used on multiple characters?
Single quotes in C++ are used to denote characters, not strings. When you use single quotes around multiple characters or strings, C++ compiler will treat it as a multi-character literal, which will be stored as an integer value, representing the combined ASCII values of those characters. In this article, we will learn all about single quotes in C++ and how they behave when used with multiple characters.
Single Quotes in C++
In C++, single quotes are used to represent a single character. For example, 'a' is a character literal representing the english alphabet 'a'. For each character, C++ assigns a unique integer value based on the ASCII table.
char singleChar = 'a'; cout << "Single character literal: " << singleChar << endl; // Output: a
Single Quotes with Multiple Characters
When you use single quotes with multiple characters, like 'abc', C++ treats it as a multi-character literal. And when you try to print it to console, you will get a random integer value, which is the combined ASCII values of those characters. Let's see an example:
Example
In the code, below we will use single quotes with multiple characters and print the result.
#include <iostream> using namespace std; int main() { cout << 'testing'; return 0; }
The output of the above code will be:
1953066599 Warnings/Errors: main.cpp:5:13: warning: character constant too long for its type 5 | cout << 'testing';
As you can see, the output is not 'testing', but rather a random integer value (1953066599 in this case). Along with output, you might also see a warning from the compiler saying "character constant too long for its type".
Why Integer Value For Multi-Character Literal?
When you use single quotes with multiple characters, C++ treats it as a multi-character literal. The compiler combines the ASCII values of those characters into a single integer value. This is why you see an integer output instead of the expected string.
For example, in this case the resulted integer "1953066599" is obtained by:
't' == 0x74; 'e' == 0x65; 's' == 0x73; 't' == 0x74; 'i' == 0x69; 'n' == 0x6e; 'g' == 0x67; 0x74657374696e67 is 1953066599.