Understanding std:: Prefix

Why do some code examples online use std::cout instead of just cout?

You'll often see two different styles for using things from the C++ standard library:

Style 1: using namespace

In our introductory lessons, we add a using namespace std; statement near the top of our files:

#include <iostream>
using namespace std;  

int main() {
  cout << "Hello\n";     // no std:: needed
  string name{"World"};  // no std:: needed
}

Style 2: Explicit std::

We can remove this, and instead use the std:: prefix any time we want to use a capability from the C++ standard library:

#include <iostream>

int main() {
  // explicitly showing these come from std
  std::cout << "Hello\n";  
  std::string name{"World"};  
}

Both styles work perfectly fine, but there are good reasons why many developers prefer using std::.

Benefits of Using std::

Code Clarity:

  • It's immediately clear where things come from
  • Helps when reading unfamiliar code
  • Makes it easier to spot what features you're using

Avoiding Naming Conflicts:

#include <string>

namespace game {
class string {};  // our own string class
}

int main() {
  // clearly using std::string
  std::string text{"Hello"};

  // clearly using our string
  game::string gameText{};
}

Professional Practice:

  • Many companies require this style in their coding standards
  • It's common in open source projects
  • Makes code more maintainable in large projects

Remember: For this course, either style is fine - just be consistent within each program. As you progress to larger projects, you'll develop a preference based on your needs and team standards.

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.

Why Text Needs Quotes
Why do we need to use double quotes for text but not for numbers?
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 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