Welcome guest. Before posting on our computer help forum, you must register. Click here it's easy and free.

Author Topic: why is using namespace std foolish in c++?  (Read 7454 times)

0 Members and 1 Guest are viewing this topic.

DaveLembke

    Topic Starter


    Sage
  • Thanked: 662
  • Certifications: List
  • Computer: Specs
  • Experience: Expert
  • OS: Windows 10
why is using namespace std foolish in c++?
« on: November 11, 2017, 03:16:52 PM »
 Was looking over some code and the repetition of std::cout instead of using  using namespace std caught my attention as why all these extra keystrokes to type std:: before each cout when using the global using namespace std I thought was the way to go. From digging on google it looks like this using namespace std is older coding method and according to one commenter "foolish" but no reason as to why its foolish.

Below is the comment that grabbed my attention and decided to ask here whats foolish about coding that way and saving from having to type std:: prepended to every cout .... Its an output so... it cant make for an overflow that I know of  :-\

Quote
If you've foolishly dumped some of the standard library into the global namespace with using namespace std; then it means the same as std::cout.

https://stackoverflow.com/questions/25807082/difference-between-stdcout-and-cout

Salmon Trout

  • Guest
Re: why is using namespace std foolish in c++?
« Reply #1 on: November 11, 2017, 03:19:52 PM »
Maybe this...

https://stackoverflow.com/questions/4043930/is-using-namespace-like-bad

Quote
It's primarily about good housekeeping. If you're not really going to use more than a few identifiers in a namespace, why clutter up your own namespace by dumping all of the identifiers from that namespace into yours?

DaveLembke

    Topic Starter


    Sage
  • Thanked: 662
  • Certifications: List
  • Computer: Specs
  • Experience: Expert
  • OS: Windows 10
Re: why is using namespace std foolish in c++?
« Reply #2 on: November 11, 2017, 03:43:35 PM »
Thanks Salmon... Google wasnt hitting on matches to "foolish" other than the one that I had found and "BAD" shows lots on this subject with exact reasons why like what you linked.

Reading up on this it looks like I need to break my legacy using namespace std method and force myself to make a habit of prefixing std:: before cout, cin, and endl. It wouldnt be a problem for stuff I code, but if I were to code anything for a larger project the legacy use of using namespace std could be a problem given the right conditions.  :)

To me I was looking at this similar to how in batch you can just use @echo off and then not need to @echo. for each line making for extra keystrokes. I didnt expect it to be a naming convention issue with variables and libraries. Interesting.

Back in the day of Basic programming I so loved using ? in place of having to type PRINT  :P   I like lesser keystrokes and get the job done, but this is a situation where I should ditch the legacy habit of global namespace I guess and type the 5 extra keystrokes per use.  ::)

Sometimes I wish there was a shorthand programming method like how ? = PRINT and all that to manually code faster and as is with ? = PRINT saving 3 keystrokes per since having to press shift and then ? is 2 strokes. Maybe there is a way to define functions and call to them in short hand. I've never done that in C++ other than calling to objects for reuse, but like instead of std::cout and std::cin you can simply use ? for std::cout and | for std::cin however I'm thinking maybe it can only be done by altering a compiler to recognize this syntax and run with it as such. BASIC use to flip the ? to PRINT so when listing your program it wouldnt show ? but instead would show PRINT in place of ? as for the IDE already flipped the shorthand to longhand so even when lprint of your code to that loud dot matrix printer you didnt see ? but PRINT in proper syntax.

10 CLS
20 ?"Hello World"
30 END

but instead list would show as

10 CLS
20 PRINT"Hello World"
30 END

Shorthand programming is one of the reasons why Perl is so luring to me.  ;D

BC_Programmer


    Mastermind
  • Typing is no substitute for thinking.
  • Thanked: 1140
    • Yes
    • Yes
    • BC-Programming.com
  • Certifications: List
  • Computer: Specs
  • Experience: Beginner
  • OS: Windows 11
Re: why is using namespace std foolish in c++?
« Reply #3 on: November 11, 2017, 05:32:14 PM »
"using namespace X" is not the same as imports or uses in other languages like Java or C#. It is largely these differences which make it a poor practice. With Java and C# imports and uses effectively tell the compiler "if you don't understand an identifier, try looking in these packages and namespaces before you give up". But in C++ using namespace X means to bring everything in that namespace into the global namespace in the current scope. Whereas ambiguous names in Java packages ad C# nmamespaces just means you have to explicitly reference those namespaces when using the appropriate class, with C++ a name collision is actually a compile error on the uses namespace statement which brings in the colliding identifier.

This means if a namespace changes and adds indentifiers which now collide with your global namespace or with another namespace, you either need to remove the uses namespace altogether and make everything explicit or change your code so it doesn't conflict with the namespace, if you can even do that.


If you want "shorthands" you can define them yourself using Macros or functions. For example:

Code: [Select]
#include <iostream>
#define writeln(data) std::cout << data << std::endl
#define readln(variable) std::cin >> variable
int main()
{
    int dataread=0;
    writeln("data");
    readln(dataread);
    return 0;
}

You cannot use a question mark or pipe symbol here since the macro has to be a valid identifier. You could make macros for say i and o for each one.

Then the macro includes the namespace reference. Same if you were to do this via a separate function. (a separate function, by the way, can use using namespace... right within the function. You can use the using namespace... statement at any scope- it doesn't need to be at the start of the file).

As an aside, Source Code isn't supposed to be "easy to write" and striving to reduce keystrokes is counter-productive. You should be writing it so that it is easy to read, which means longer more descriptive identifiers. For example, Take this function: I doubt somebody even needs to know C# or have any understanding of the massive libraries that it is part of to understand what is happening here.

Code: [Select]
private bool ProductSuiteApplies(ReportInformation reader)
    {
        var productType = Config.Static.Get<SuiteInformation.ProductTypeConstants>("General.ProductType");
        String SuiteDesc = SuiteInformation.GetProductDescription(productType);
        String Abbrev = SuiteInformation.GetProductAbbreviation(productType);
        return reader.ApplicableSuites.Length > 0 ||
               reader.ApplicableSuites.Contains(SuiteDesc) || reader.ApplicableSuites.Contains(Abbrev);
    }

Imagine if it was using "shorthand" or quick and dirty variables, though:

Code: [Select]
private bool CheckSt(RInf r)
    {
        var pt = Cfg.Get<SInfo.Types>("G.Type");
        String sd = SInfo.GetPD(pt);
        String abv = SInfo.GetPA(productType);
        return reader.AS.Length > 0 ||
               reader.AS.Contains(sd) || reader.AS.Contains(Abv);
    }

It would require looking at the functions/methods that are being called to know what it is even doing. What is a "St"? Well, aside from saving a few characters, A completely opaque identifier.
I was trying to dereference Null Pointers before it was cool.

DaveLembke

    Topic Starter


    Sage
  • Thanked: 662
  • Certifications: List
  • Computer: Specs
  • Experience: Expert
  • OS: Windows 10
Re: why is using namespace std foolish in c++?
« Reply #4 on: November 11, 2017, 09:05:24 PM »
Thanks BC for your input on this. Pretty Cool that you can shorthand by defining for readline and writeline. I was thinking the compiler would have to have rules on how to handle a shorthand, and you proved that it can be done with a standard IDE.

Regarding looking at the other C# code I agree that to others working with your code being as descriptive as possible is probably best in whats doing on to follow it without having to look up functions. I tend to not be as descriptive in the actual function variables and pointers but put description in my comments, however I see now that with a well descriptive function or method I can actually ditch the comment lines and have it self descriptive which saves keystrokes I suppose. At times I do tend to still go with short variable names such as CIN>>A; and CIN>>Acct; would be a better habit and to be proper STD::CIN>>Acct; to avoid the using namespace std and Acct is easily identifiable as Account.

Having been messing with programming since I was 10 with BASIC and not sticking to any one language to master but knowing enough to put stuff together when needed has made for some bad habits. s well as sometimes I have even programmed in a mix of C and C++ and the IDE is happy with it due to legacy support but its a mess to professional programmers. Grins knowing you have seen some of my rube Goldberg code examples here over the years as well as some problems I have run into due to this. I feel like a jack of many programming languages but master of none. But I am able to piece together ways to get the job done however sometimes not as efficient in execution or vulnerable to overflow conditions because the input isn't tested for length etc because I am using the program myself and wont intentionally overflow it. However some interesting problems arise when I forgot for example that the first element of an array is 0 and not 1 and my program called to memory outside of the scope of the array. Lesson learned and fortunately I caught it and fixed it. Or when I look at the code and it starts at 0 and ++ increments to 1 and then reset back to 0 and I am getting 1111111 as an output because for some reason while the code structure shows that it should reset back to 0 and then increment again to 1 and after it did the flop to the flip reset back to 0 to use 2 arrays in a concatenation it was found that I needed to set the value to -1 to get my 0101010101 which I was looking for with my flipflop issue about a year ago.

Thanks for your patience with my questions and descriptive examples.


Geek-9pm


    Mastermind
  • Geek After Dark
  • Thanked: 1026
    • Gekk9pm bnlog
  • Certifications: List
  • Computer: Specs
  • Experience: Expert
  • OS: Windows 10
Re: why is using namespace std foolish in c++?
« Reply #5 on: November 11, 2017, 09:45:19 PM »
Quote
needed to set the value to -1
Yes, that was documented somewhere in the Intel assembly language for the 8080.
Now way can I find it, but it is called 'Two's complement' arithmetic. It is the standard for Intel machine code in the 8086 family.
So you define:
FALSE = 0
TRUE = -1
And it is also part of the Microsoft Basic stuff.
That goes back to about 1975, I think.
Modern reference:
https://www.cs.cornell.edu/~tomf/notes/cps104/twoscomp.html
Quote
Two's complement is not a complicated scheme and is not well served by anything lengthly. Therefore, after this introduction, which explains what two's complement is and how to use it, there are mostly examples.
Two's complement is the way every computer I know of chooses to represent integers. To get the two's complement negative notation of an integer, you write out the number in binary. You then invert the digits, and add one to the result.
That is as much as anybody needs to know.  ::)