saving . . . saved namespace?? has been deleted. namespace?? has been hidden .
namespace??
Title
Question
plz clarify the importance of "using namespace std" in the cpp programming code

C-and-Cpp First-Cpp-Program 3-4 min 20-30 sec 29-12-16, 11:27 p.m. rashmisinha693

Answers:

Dear Rashmi Sinha,

The answer to your question is in the tutorial at "First Cpp Program"between 02:52 and 03:11. Pls watch the tutorial and listen to the explanation between the mentioned time.

Nancy Varkey
ST Team


31-12-16, 7:48 a.m. nancy


Namespacing is a way to wrap code into "segments" so that your code does not conflict with others. For example, Lets say that I create a program for multiplying two numbers. I put the code in a function called:

int multiply(int a, int b) { return a * b; }

Now suppose, you use my code in your program. But your program also has a multiply function with the same signature. but the function does something different than mine. Say:

int multiply(int a, int b) { static int c = 0; c--; return a*b*c; }

Now that's a problem. How would you solve this problem? You could just change the name of your function, or mine, but what if there are thousand places where I used my function in my program that you imported. Would you change all their names? That's not very smart. So to fix this problem, we have namespacing.

Consider my program, but this time, inside a namespace.

namespace MyProgram {
int multiply(int a, int b) { return a * b; }
}

Now if you import my code in yours, and there's a function called multiply with the same signature in your code, there would be no conflicts. Because, now, my function is now MyProgram::multiply, inside a namespace. And if you want to use it, you will have to write MyProgram::multiply(_arg1, _arg2);

But what if your program does not have a multiply function? Then it would be just a pain to write MyProgram::multiply everytime you want to use my function. To fix this, we import the namespace in our prgram. To do so, we use the keyword "using". So:

using namespace MyProgram;

Adding this to the top of the code, will allow you to use the function multiply(_arg1, _arg2) anywhere below it without having to specify the namespace.

In a similar way, "std" is the namespace of the Standard Library offered by C++. All C++ library functions and containers are enclosed inside the std namespace. So you put using namespace std; at the top of the code to use the library functions, containers, without specifying the namespace, such as cout, cin, vector, map, etc. These are actually std::cout, std::cin, std::vector, etc.

Try removing that line & then use "cout" to output and see what happens!
21-02-17, 8:23 p.m. mehdi3468@gmail.com


Log-in to answer to this question.