Jun 6, 2020

using namespace std; | std::cout | std::cin | C++ programming basics |

using namespace std;

Hey people in this blog you are going to read about “ using namespace std; ”, Namespaces are used in the C++ programming language to create a separate region for a group of variables, functions and classes etc.

Consider this, there are two students having same names, when we need to differentiate them, we would have to use some other information along with their names. Same goes with namespaces in C++, you might have a variable name, math, in your program, and there may be a library which contains a variable named math. Here, no way the compiler gonna recognize which version of variable value is called. That’s why namespace is designed to overcome this difficulty.

Now, namespace std:


std is an abbreviation, std is the standard namespace. “cout”, “cin” and a lot of other things are defined in it.

So whenever the execution will take place and come across cout, cin, endl or anything, it will read it as std::cout, std::cin, or std::endl.


A sample program :

Basically we only learn what we are taught. But coding isn’t just fluttering in a given consignment for the whole life, you have the sky to reach.

Namespaces are used for other purposes also.

Creating namespace:

The C++ language include the keyword “namespace” for creating namespaces



Take a look at the following code:



We can make the above code simple by doing this: using namespace measurements; 

e.g.  cout<<endl<<”Area is: “<< area;

Points to ponder on :

1) 1. We can have more than one namespace of the same name.

2) 2. We can have anonymous namespaces (namespace with no name). They are directly usable in the same program and are used for declaring unique identifiers. It also avoids making global static variable. The “anonymous” namespace you have created will only be accessible within the file you created it in.

For example look at the code below:


Check the result!!

 

Anyway, when there is a boon there is a bane too.

Most of the professional coders don’t prefer, “using namespace std” , as a good practice.

They say what if one or two of your function is names ‘Min()’ or ‘Max()’?

It will get collide with std::max, as using “using namespace std” is global.

In certain places, it is permitted to have a using declaration, which is of the form using ::foo::bar;

Look at the code below.


This is a little extreme with just one program, but you get the idea.

Imporant note:

Why we use, "int argc" and "char *argv" ?

They are used to control program from outside instead of hard coding those values inside the code. argv[argc] is a NULL pointer. argv[0] holds the name of the program. argv[1] points to the first command line argument and argv[n] points last argument.


We also have something on "Dynamic Memory Allocation in C/C++", check it out by clicking here.

No comments:

Post a Comment