Setting up a C++ Development Environment

Understanding namespace std

Why do we need to write using namespace std; - what happens if we remove it?

3D art showing a blacksmith character

The line using namespace std; is a convenience feature that lets us use things from the standard library without typing std:: before them. Let's see what happens when we remove it:

#include <iostream>
using namespace std; 

int main() {
  // won't compile without std::
  cout << "Hello World!\n";  
}
error: 'cout' was not declared in this scope

To fix this, we need to specify that we're using cout from the std namespace:

#include <iostream>

int main() {
  //  works fine with std:: prefix
  std::cout << "Hello World!";  
}
Hello World!

Why Namespaces Exist

Namespaces help prevent naming conflicts. Imagine two different libraries both have a function called print():

#include <iostream>

namespace printerLib {
void print() {
  std::cout << "Printing document...\n";
}
}

namespace graphicsLib {
void print() {
  std::cout << "Drawing to screen...\n";
}
}

int main() {
  // we know exactly which print() to use
  printerLib::print();

  // no confusion about which one we mean
  graphicsLib::print();
}
Printing document...
Drawing to screen...

Why Some People Avoid using namespace std

While using namespace std; is fine for learning and small programs, many developers prefer to explicitly write std:: because:

  • It makes it clear where things come from
  • It prevents potential naming conflicts in larger programs
  • It's considered more professional style

You can also be selective about what you import:

#include <iostream>

using std::cout;  // only import cout 

int main() {
  // cout works without std::
  cout << "Hello World!";

  // endl still needs std::
  cout << std::endl;
}

For this course, using using namespace std; is perfectly fine - just be aware that you'll see both styles in real-world code.

Answers to questions are automatically generated and may not have been reviewed.

3D art showing a progammer setting up a development environment
Part of the course:

Intro to C++ Programming

Become a software engineer with C++. Starting from the basics, we guide you step by step along the way

Free, unlimited access

This course includes:

  • 60 Lessons
  • Over 200 Quiz Questions
  • 95% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved