-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
wiki: avoid
using namespace std;
in C++ (#53)
- Loading branch information
Showing
2 changed files
with
41 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
--- | ||
title: "C++" | ||
description: "A collection of useful C++ usage and tips." | ||
--- | ||
|
||
## Avoid `using namespace std;` | ||
|
||
It is common to encounter `using namespace std;` in various C++ sample codes, as it negates the need to prefix `std::` before each standard library object. However, it is not recommended to use it in your code. The reason is that `using namespace std;` might cause name conflicts. | ||
|
||
Consider a scenario where you have a function or variable named `max`. If you declare `using namespace std;`, then you will get an error when you try to use `max` because it conflicts with `std::max`. | ||
|
||
```cpp | ||
#include <iostream> | ||
using namespace std; | ||
|
||
int max = 0; | ||
int main() { | ||
cout << max << endl; // error: reference to 'max' is ambiguous | ||
} | ||
``` | ||
|
||
To avoid the preceding error, use the following code instead: | ||
|
||
```cpp | ||
#include <iostream> | ||
|
||
int max = 0; | ||
int main() { | ||
std::cout << max << std::endl; // 0 | ||
} | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters