Using namespace std vs other alternatives [duplicate] - c++

This question already has answers here:
Why is "using namespace std;" considered bad practice?
(41 answers)
Closed 8 years ago.
using namespace std;
So far in my computer science courses, this is all we have been told to do. Not only that, but it's all that we have been allowed to do, otherwise we get penalized on our code. I understand, through looking at code posted online, that you can use ::std or std:: to accomplish the same thing.
My question is generall why? Obviously for the sake of learners and simplicity using the global declaration is simpler, but what are the draw backs? Is it more realistic to expect ::std in a real world application? And I guess to add on to this, what is the logic/concept behind the using declaration? None of this has been explained during my courses, and I'd like to get a better grasp on it.
As a general question: if I haven't been taught this content, vectors, templates, classes, or error handling does it seem like I'm missing a lot of essential C++ functionality?
Thanks in advance!

This is really one of those things that you can discuss over beer for hours and hours, and still not have an answer everyone is happy with.
If you are nearly always using std:: functionality, then adding using namespace std; at the beginning of the file is not that bad an idea. On the other hand, if you are using things from more than one namespace (e.g. writing a compiler using llvm:: and also using std::, it may get confusing as to which parts are part of llvm and which parts are std:: - so in my compilter project, I don't have a single file with using namespace ...; - instead I write out llvm:: and std:: as needed. There are several functions (unwisely, perhaps) called Type(), and some places use something->Type()->Type() to get the type-thing that I need... Yes, it confuses even me a little at times...
I also have many things that look like Constants::ConstDecl and Token::RightParen, so that I can quickly see "what is what". All of these COULD be made shorter and "simpler", but I prefer to see where things belong most of the time.
Being more verbose helps making it easier to see where things belong - but it makes for more typing and more reading, so it is a balance.

I'd say that generally, you do not declare the use of std globally. I guess if you're making a simple application, that would suffice. However, when you work in a large organization you often times have different namespaces that are used, and those might have overlapping objects. If you have a function in std, and in a namespace that you created, and then call "using namespace std" AND "using namespace yournamespace", you'll get unwanted results when calling that function. When you prefix every call with the namespace, it keeps it clearer and doesn't give issues with overlap.

general why?
Naming things is one of the more difficult aspects of software development. Beginners simply have little idea of how their name choices might generate ambiguities later on.
In particular, our software jargon often has preferred terms for certain issues. These preferences can cause unrelated class instances to be developed with the same (or similar) symbol with similar meanings.
Some of my often used symbols include init(), exec(), load(), store(), and I use timeStampGet() lots of places. I also use open(), close(), send()/recv() or write()/read().
So, I could rename init() in each of the 3 name spaces, and 5 objects into which I have added it, but it is much simpler to specify which one I want.
I find exec() in 2 name spaces and 12 objects. And there are 3 different timeStampGet() methods that I use. Whether namespaces or functions or class methods, these symbols make sense to me.
Furthermore, I find the 5 char "std::" namespace-as-prefix completely natural, and much preferable to the global "using namespace std". I suppose this comes with practice.
One more item - any where a larger name space or class name becomes tiresome, I sometimes add a typedef short name ... here are some examples from production code:
typedef ALARM_HISTORY ALM_HST;
typedef MONITOR_ITEM MI
typedef BACKUP_CONTROL BC;
On one team, we agreed to use well defined 'full' names, which, occasionally, became tiresome because of the length. Later in the project, we agreed that typedefs (for short class or namespace names) could be used when they were simple and added no confusion.

Personally I hate 'using' declarations. To me they make code unreadable and you break namespaces. I've spent 20 years as a maintenance programmer and I hate anything that make the code harder to read - in my mind using is as useless as throw specifications.
What is more readable 6months - a year - 10 years down the line
UDP::Socket sock
sock.send(data)
TCP::Socket sock2
sock2.send(data)
vs
using UDP;
using TCP;
sock.send(data)
sock2.end(data)
I also don't like namespace aliases
using namespace po = boost::program_options;
Now you are making the next programmer work harder with an extra level of indirection looking up what po is compared to boost::program_options. Same goes for those horrible typedef of
typedef long QUADWORD;
What size is a quadword - how long is a long 4 bytes? 8 bytes maybe 17 bytes on my OS
My last take is if you cannot type then don't be a programmer - a saved keystroke != good maintainable code

Related

What does std stand for?

I understand that if there is no using namespace std, and you want to write a cout, you need to have a std::cout.
What does the std represent? Why is std widely used, e.g. std::vector, std::cout, and std::cin?
std stands for "standard".
The reason why so much standard stuff goes in the std namespace is simple: Before namespaces, different code written by different people would often use the same name and cause a conflict. For example, my drink dispenser program from 1994 might have a class ofstream which is an orange fanta stream. When a new version of C++ came along and added ofstream which was an output file stream, my program wouldn't compile any more, or it'd crash.
Okay, orange-fanta-stream is silly, but major operating systems do have C functions called open, close, and index. I'm sure many people have tried to make global variables called open, and then their programs have crashed.
In C++, all the new C++ standard stuff is inside std::, so as long I don't call something in my program std, they can add new stuff inside std:: and it definitely won't cause this problem. Unfortunately all the stuff that C++ inherits from C is outside std::, so you still can't make a global variable called open (on Linux), but at least it's a start.

Is it still considered bad practice when I use “using std::cout;” and so on? [duplicate]

This question already has an answer here:
C++ - Best Practice: `using std::cout` vs `std::cout` [closed]
(1 answer)
Closed 1 year ago.
It's obvious why using
using namespace std;
is considered bad practice. As I'm fairly new to C++ (about 8 months now) I wondered if it is still considered bad practice when I use
using std::cout;
using std::cin;
using std::endl;
and so on to only include what I need instead of including the whole namespace. My old teacher always told us to not use that as well but my new teacher told us it's just fine to use the using-Declaration compared to including the whole namespace.
What do you use and would you consider it a bad practice or not?
I hope this question is not a duplicate but I did not find another question like this, just questions about why it's considered to be bad practice to use using namespace std;, but like mentioned above I already know that.
I didn't like my original answer, too wordy, so here's a better rewrite.
Here's a good answer on why using namespace is bad.
With that answer in mind, if the library Foo has function kept and Bar has the function lept. With 2 using-directives, you can use both kept and lept without the scope. If Foo decides to update, and adds a function lept, then your compiler of choice will either give an error, or have undefined behavior*. If you use using Foo::kept and using Bar::lept, then an update on Foo that adds lept will not cause any error, and you can use Foo::lept to call that new function. It is also considered proper form with using-directives to not use them globally. Rather, for each function that you want to use a using-directive, redefine it. It is not bad practice to use using std::cout and the like, and in some instances, allows for quick library changes. For instance, I am using a JSON parsing library. To test them all, I added a using json = LIBRARY::json line to the start of my program, allowing me to quickly change out libraries if I did not like the one I had.
*For example, if Bar has lept defined as double lept(double, double), but Foo has lept defined as int lept(int, int), then a call to lept with 2 int inputs would call to Foo::lept or give an error on compile time. This means you won't know you have a massive error in your program until you test it.

C++ problems with string

I am doing some arduino development using cpp and h files and I am having some troubles using string with them. Currently I have
#include <string>
at the top of both the cpp and the h file. When I do that it gives me the error:
string: no such file or directory
If I go into the h file and change it to
#include <string.h>
then it gives me the error:
std::string has not been declared
Anytime I use the string I use: std::string to declare it. I am not using namespace std and these files were working together fine before I started to try to use string. I am new to C/C++ so I appreciate any help. Thanks!
In short, there is a way to use std::string with the Arduino.
TL;DR:
link to the arduino STLv1.1.2
NOTE
Please note that currently the harrdwareserialstream class provided by this STL should be considered broken (as per my testing, with version 1.6.5 of the IDE, and possibly anything after 1.0.6). therefore, you can't use
hardwareserialstream << "Hi there person number " << (int)i
and so on. it seems to no longer work due to taking a reference to the serial port it would interact with rather than a pointer - in short, continue using
Serial.print("Hi there person number");
Serial.print((int)i);
Lastly the serial classes don't know what a std::string is, so if using them, give it std::string.c_str() instead
Background
As McEricSir says in the comments, the arduino does provide its own string class, though i have found it to have problems related to memory leakage, which eventually ate all of the memory i had and the program stopped running - though this was in the arduino IDE v 1.0.5, it may have been fixed since then.
I had the same problem, and found someone who had created a version of the STL for the arduino (props to Andy Brown for this) which is a cutdown version of the SGI STL. it provides std::string, std::vector and a large amount of the STL to the arduino.
there are some things to be aware when using it though; if you have a board with very little memory, you will fill it quite quickly using the smart containers and other advanced features.
Using the Library
To use the library, you'll need to read the article, though I'll summarise the main points for you here:
Installation
simply extract the library to (assuming you are using the standard Arduino IDE) hardware\tools\avr\avr\include folder and you are good to go.
Using It
To actually use the new libraries, you need to include 2 additional things as well as the library you wanted.
firstly, you need to include the header iterator BEFORE any libraries that come from this STL - and in every file you reference the STL in.
Secondly, you also need to include the file pnew.cpp to provide an implementation of the new operator for the STL to work with.
Lastly, include any header files as you would normally.
to make use of the types gained from them, don't forget the the std:: namespace notation for them. (std::string and so on)
Bugs with it
Since Andy posted the library, there have been two bugs (that i'm aware of).
The first one Andy himself rectifies and explain in the blog post:
The compiler will spit out a typically cryptic succession of template errors, with the key error being this one:
dependent-name std::basic_string::size_type is parsed as a non-type,
but instantiation yields a type c:/program files (x86)/arduino-1.0/
hardware/tools/avr/lib/gcc/../../avr/include/string:1106: note:
say typename std::basic_string::size_type if a type is meant
Basically the STL was written a long time ago when C++ compilers were a little more forgiving around dependent types inherited from templates. These days they are rightly more strict and you are forced to explicitly say that you mean a type using the typename keyword.
Additionally, he provides the updated version for you to grab.
Lastly, there are reports in the comments about a bug in the newer versions of the IDE pertaining to the vector class where the compiler complains about the use of _M_deallocate without a prepending this->, which you can fix if you search for them inside the vector class
For your convenience
As i use this quite frequently, i've packaged up the current version, which can be found here (this includes both the fixes i have commented on)
Lastly
When using this, make sure to keep an eye on your free memory, and to that end i recommend the excellent class MemoryFree Library found here
on a side note if you #include<string> inside the header you won't need to include it in the relevant .cpp file

C++ namespace elements

I want to get namespace elements name and value... how can I do that?
I want to list names and values (edited)
example
namespace testns{
int stuff=4;
};
int index=0;
get_element_name(testns,index);
get_element_value(testns,int,index);
A namespace is just what it says on the box, a namespace. You can have the same namespace in many modules, how would you know how to index them? What is the one and only proper order? Namespaces are only to categorize elements, not to somehow magically allow them to be indexed.
C++ does not have any reflection facilities (I assume that is what you are looking for). You have to manually state what you want.
What you're trying to do is called reflection, and C++ doesn't have any language-level built-in way of doing this for you. There are only a few things that can be done, such as using the # operator within a #define, but then you're using #defines, which I bet is not what you want.
The closest thing you can functionally get is to write another program which reads your source, digs out the namespace information, then writes it to a header file you can #include somewhere else. The GCC-XML extension could be helpful in this regard, since it uses the G++ front end to parse the language, then outputs the syntax trees as XML, which you can read with any number of XML DOM parsers.
In order to access the variable stuff, you do this:
//Setting
testns::stuff = 10;
//Getting
int stuff_value = testsn::stuff;
The purposes of namespaces are to disambiguate between code which use similar nomenclature.

Why is the C++ syntax so complicated? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 13 years ago.
I'm a novice at programming although I've been teaching myself Python for about a year and I studied C# some time ago.
This month I started C++ programming courses at my university and I just have to ask; "why is the C++ code so complicated?"
Writing "Hello world." in Python is as simple as "print 'Hello world.'" but in C++ it's:
# include <iostream>
using namespace std;
int main ()
{
cout << "Hello world.";
return 0;
}
I know there is probably a good reason for all of this but, why...
... do you have to include the <iostream> everytime? Do you ever not need it?
... same question for the standard library, when do you not need std::*?
... is the "main" part a function? Do you ever call the main function? Why is it an integer? Why does C++ need to have a main function but Python doesn't?
... do you need "std::cout << "? Isn't that needlessly long and complicated compared to Python?
... do you need to return 0 even when you are never going to use it?
This is probably because I'm learning such basic C++ but every program I've made so far looks like this, so I have to retype the same code over and over again. Isn't that redundant? Couldn't the compiler just input this code itself, since it's always the same (i.e. afaik you always include <iostream>, std, int main, return 0)
C++ is a more low-level language that executes without the context of an interpreter. As such, it has many different design choices than does Python, because C++ has no environment which it can rely on to manage information like types and memory. C++ can be used to write an operating system kernel where there is no code running on the machine except for the program itself, which means that the language (some library facilities are not available for so-called freestanding implementations) must be self-contained. This is why C++ has no equivalent to Python's eval, nor a means of determining members, etc. of a class, nor other features that require an execution environment (or a massive overhead in the program itself instead of such an environment)
For your individual questions:
do you have to include the <iostream> everytime? Do you ever not need it?
#include <iostream> is the directive that imports the <iostream> header into your program. <iostream> contains the standard input/output objects - in particular, cout. If you aren't using standard I/O objects (for instance, you use only file I/O, or your program uses a GUI library, or are writing an operating system kernel), you do not need <iostream>
same question for the standard library, when do you not need std::*?
std is the namespace containing all of the standard library. using namespace std; is sort of like from std import *, whereas a #include directive is (in this regard) more like a barebones import std statement. (in actual fact, the mechanism is rather different, because C++ does not use using namespace std; to automatically lookup objects in std; the using-directive only imports the names into the global namespace.)
I'll note here that using-directives (using namespace) are frequently frowned upon in C++ code, as they import a lot of names and can cause name clashes. using-declarations (using std::cout;) are preferred when possible, as is limiting the scope of a using-directive (for instance, to one function or to one source file). Don't ever put using namespace in a header without good reason.
is the "main" part a function? Do you ever call the main function? Why is it an integer? Why does C++ need to have a main function but Python doesn't?
main is the entry point to the program - where execution starts. In Python, the __main__ module serves the same purpose. C++ does not execute code outside a defined function like Python does, so its entry point is a function rather than a module.
do you need "std::cout << "? Isn't that needlessly long and complicated compared to Python?
std::cout is only needed if you don't import the cout name into the global namespace, either by a using-directive (using namespace std;) or by a using-declaration (using std::cout). In this regard, it is once again much like the distinction between Python's import std and from std import * or from std import cout.
The << is an overloaded operator for standard stream objects. cout << value calls cout's function to output value. Python needs no such extra code because print is built into the language; this does not make sense for C++, where there may not even be an operating system, much less an I/O library.
do you need to return 0 even when you are never going to use it?
No. main (and no other function) has an implicit return 0; at the end. The return value of main (or, if the exit function is called, the value passed to it) is passed back to the operating system as the exit code. 0 indicates the program successfully executed - that it encountered no errors, etc. If an error is encountered, a non-zero value should be returned (or passed to exit).
In response to your questions at the end of the post, it can be summed up with the philosophy of C++:
You don't pay for what you don't use.
You don't always need to use stdin or stdout (Windows/GUI apps?), nor will you always be using the STL, nor will everything you write necessarily use the standard main (winAPI) etc. As a previous poster said, C++ is lower level than Python. You will be exposed to more of the details, which offers you more control over what you're doing.
... do you have to include the
everytime? Do you ever not
need it?
You don't need it if you're not going to use iostreams in that module. In larger programs, few modules do any actual IO directly, and so few actually need to use iostreams.
Turning the question around: in python you need to import sys and/or os in most non-trivial programs. Why?
... same question for the standard
library, when do you not need std::*?
You can have the using line or you can use the std:: prefix. This is very similar to the choice python gives you of either saying "from sys import *" or "import sys" and then having to prefix things with "sys.". In python you have to say "sys.stdout". Is "std::cout" really any worse?
... is the "main" part a function? Do
you ever call the main function? Why
is it an integer? Why does C++ need to
have a main function but Python
doesn't?
Yes, main is a function. Typically you wouldn't call main yourself. The name "main" is reserved for the entry-point of your program. It returns an integer because the value returned is used as the status code of your program. In Python you can use sys.exit if you want to return a non-zero status code.
Python doesn't have the same convention because with Python you can have code in a module not in a function. This code is executed when you load the module. Interestingly, many people feel it is bad style to have code at the top-level of a module and will instead create a main function by doing something like this:
def main(argv):
# program goes here
return 0
if __name__ == '__main__':
sys.exit(main(sys.argv))
Also, in Python you tell the interpreter with module is the "main" module when you run it. eg: "python foo.py". In C, the "main" module is (effectively) the one with a function called main. (If there are multiple modules with a main function, it's a linker error.)
... do you need "std::cout << "? Isn't
that needlessly long and complicated
compared to Python?
The equivalent in Python is actually "sys.stdout.write(...)". Python's print statement is a special-case short-hand.
That said, many people do feel the iostreams convention of using bit-shifting operators for IO was a bad idea. Ironically, Python seems to have been "inspired" by this syntax. If you want to use print to write to somewhere other than stdout you can say:
print >>file, "Hello"
... do you need to return 0 even when
you are never going to use it?
You aren't going to use it, but your program will. As mentioned earlier, the value you return is the status code of your program.
Aside: I actually do feel that C++ is overcomplicated, but not because of any of the points you mention. All of the differences you mention go away (in the sense that you need just as much complexity in Python) once you start writing non-trivial programs that have multiple modules and do more than just writing to stdout.
You include <iostream> when you want to output things to the console. Since printing "Hello world" involves console output, you need iostream.
The main function is called by the operating system, basically. It gets called with the command-line arguments passed to the program. It returns an integer because the program must return an error code to the operating system (this is the standard way for determining if the last command was successful).
You can always use printf("hello world"); instead of std::cout << "hello world"; if you want to go C style. It's a bit quicker to write and lets you do formatted output.
You return 0 from main to indicate that the program executed successfully.
The compiler does not automatically include all the standard libraries and use namespace std because sometimes name collisions can result between your code and library code that you may not actually need at all. You don't always need all the libraries. Likewise, sometimes you are using a different main routine (Windows development comes to mind with its own, different WinMain starting function). The compiler also does not automatically return 0 because sometimes the program needs to indicate that it completed unsuccessfully.
There are good reasons for all these things. C++ is a very broad language it is used for everything from small embedded systems to giant applications built by 100s of programmers. The use case of a guy building a small program to run on a desktop is by no means the only one. So sometimes you are building library components. In that case no main(). Sometimes you are working on a tiny system with no standard library. In that case no std. Sometimes you want to build a Unix tool that works with other Unix text tools and signals its completion status with an int returned from main().
In other words the things you complain about are boilerplate to you. But they are vital details that vary to other users of the language.
This reminds me of The Evolution of a Programmer. Some of the languages and technologies demonstrated are a bit dated now, but you should get the general idea. :)
One of the reasons C++ is rather complicated is because it was designed to address problems that crop up in large programs. At the time C++ was created as AT&T, their biggest C program was about 10 million lines of code. At that scale, C doesn't function very well. C++ addresses many of the problems you get with that kind of program.
With that said, it's also possible to answer the original questions:
You would include <iostream> where it's needed. If you've got 10.000 C++ files, it's quite common that less than 1000, sometimes less than 100 will produce user-visible output.
A statement like print "Hello, world" assumes that there is a default output, but makes it hard to generalize. The cout << "Hello, world" form makes it explicit where the output goes, but the same form also allows cerr << "Goodbye, world" and MyTmpFile << "Starting phase #" << i
The standard library is in the std:: namespace. My 10.000 files will be in an additional 25 namespaces.
main is an oddity in many ways, being the startup function.
Baldur:
You don't always need <iostream>. The only things that you will always need are:
A main function (or a WinMain, if you're writing Win32 apps).
Variables, functions, operators, language constructs (if, while, etc.).
The ability to include functionality from libraries into your program.
Everything else is application-specific.
As other posters say, the return value of the main function is an error code1. If main returns 0, be happy: everything worked OK!
1This is useful when you write programs that "communicate" with other programs. The most simple way that a program can "tell" another whether it executed properly is using an error code.
As people have said, the simple answer is that they're different languages, with different goals. To answer your specific questions...
... do you have to include the <iostream> everytime? Do you ever not need it?
<iostream> is one of the header files for iostreams, the part of the C++ standard library responsible for input/output; in this instance, you need it to gain access to std::cout. If you're not doing I/O operations in a source file, you don't need to include it -- for example, most files containing class definitions probably won't need <iostream>.
... same question for the standard library, when do you not need std::*?
std is the name of namespace containing classes in the standard library; it's there to avoid name collisions. Python has packages and modules to do this.
You can use the using statement to bring items from another namespace into your current scope, see this FAQ entry for an example (and an explanation of why it's bad to blindly bring all of std into scope!).
... why is the "main" part a function? Do you ever call the main function? Why is it an integer? Why does C++ need to have a main function but Python doesn't?
Executable statements in C++ have to be contained within a function, and the main function is defined as where execution begins. In Python, executable statements can be placed at the top-level of a file, and execution is defined to .
You can call main() if you wish -- it's just a function, after all -- but there's not often a reason to do this. Behind the scenes, most implementations of C++ call main() for you once some startup housekeeping has been done by the runtime library.
The return value of main() is returned back to the operating system. This stems from C and UNIX, in which application programs are required to provide a 1-byte exit status code, and returning that value from main() is a clear way of expressing this.
... why do you need "std::cout << "? Isn't that needlessly long and complicated compared to Python?
This is just a design difference. iostreams is a fairly complex beast with lots of features, and one of the side-effects of this is that the syntax is a bit ugly for simple tasks at times.
... why do you need to return 0 even when you are never going to use it?
You do use it; this is the value returned to the operating system as the exit status of the program.
Python is high-level language. C++ is middle-level language.