From 0523969defcb51df919963bbbd2cd7c4ffc38513 Mon Sep 17 00:00:00 2001 From: Aolin Date: Wed, 13 Dec 2023 10:06:13 +0800 Subject: [PATCH] wiki: avoid `using namespace std;` in C++ (#53) --- website/docs/cpp/cpp-wiki.md | 31 +++++++++++++++++++++++++++++++ website/sidebars.js | 10 ++++++++++ 2 files changed, 41 insertions(+) create mode 100644 website/docs/cpp/cpp-wiki.md diff --git a/website/docs/cpp/cpp-wiki.md b/website/docs/cpp/cpp-wiki.md new file mode 100644 index 0000000..da1aa18 --- /dev/null +++ b/website/docs/cpp/cpp-wiki.md @@ -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 +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 + +int max = 0; +int main() { + std::cout << max << std::endl; // 0 +} +``` diff --git a/website/sidebars.js b/website/sidebars.js index a607735..f30f2b5 100644 --- a/website/sidebars.js +++ b/website/sidebars.js @@ -45,6 +45,16 @@ const sidebars = { ], }, 'git-wiki', + { + type: 'category', + label: 'C++', + link: { + type: 'generated-index', + }, + items: [ + 'cpp/cpp-wiki' + ], + }, { type: 'category', label: 'Python',