Why Text Needs Quotes

Why do we need to use double quotes for text but not for numbers?

In C++, we use quotes to help the compiler understand exactly what we mean. When we write a number like 42, the compiler knows this is a numeric value that can be used in calculations.

But when we write text, we need a way to tell the compiler "this is just text - don't try to interpret it as anything else". Let's look at an example:

#include <iostream>
using namespace std;

int main() {
  // number - no quotes needed
  cout << 42 << "\n";

  // text - needs quotes
  cout << "42" << "\n";

  // math expression - calculates to 42
  cout << 15 + 27 << "\n";

  // text - just prints exactly what we wrote
  cout << "15 + 27" << "\n";
}
42
42
42
15 + 27

Without quotes, the compiler treats things differently:

  • 42 is a number we can do math with
  • "42" is just text that happens to contain digits
  • 15 + 27 gets calculated to give us 42
  • "15 + 27" is treated as literal text to display

This becomes really important when we start doing calculations. For example:

#include <iostream>
using namespace std;

int main() {
  // works fine - does the math
  cout << 42 + 8 << "\n";

  // this will cause some weird output!
  cout << "42" + 8 << "\n"; 
}
50

The quotes tell C++ "this is text" (technically called a string literal), while no quotes means "this is a value we can do math with". This distinction becomes even more important as we learn about variables and different types of data in future lessons.

Setting up a C++ Development Environment

Getting our computer set up so we can create and build C++ programs. Then, creating our very first application

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Program Closes Too Fast
Why does the program window close immediately after running?
Forgetting Semicolons
What happens if I forget to put a semicolon at the end of a line?
Understanding std:: Prefix
Why do some code examples online use std::cout instead of just cout?
Understanding namespace std
Why do we need to write using namespace std; - what happens if we remove it?
Cross-Platform Code
How do I make my program work on both Windows and Mac without changing the code?
C++ File Extensions
What's the difference between 'main.cpp' and other file extensions like '.txt'?
Compiling vs Running
What's the difference between compiling and running a program?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant