473,856 Members | 1,676 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

cout vs std::cout

I'm getting back into C++ after a long hiatus (they didn't have
namespaces back then).

I know this question is completely subjective, but I'd be interested in
hearing which is
the "better" style and what the pros and cons are (I'm using cout as
example, but it really
applies to any similar construct):

1) using std::cout;
cout << "This is a test";

2) std::cout << "This is a test";

The difference being prefixing every cout with 'std' or declaring it
ahead of time. The second
method could be used if cout existed in more than one spot, but how
often is that an issue?

I've seen both methods in code, but I'm seeing #2 a lot more frequently.

Sep 28 '08
58 4872
Matthias Buelow wrote:
Mark Casternoff wrote:
>I've seen both methods in code, but I'm seeing #2 a lot more frequently.

It's because many C++ programmers prefer long-winded bureaucracy over
conciseness or even (shock!) simplicity. :) Why do you think the STL is
like it is?
The STL is like /what/?
I've never heard a good reason why one shouldn't do a "using namespace
std;" at the beginning of every compilation unit.
You mean except for the fact that it might silently make your
code fail at run-time?
Maybe there're some
special cases where it might cause problems but usually not using that
is rather nonsensical, imho. The std:: is just clutter and that's
usually bad in a program.
So are static types. Let's get rid of them.

Schobi
Sep 29 '08 #11
Hendrik Schober wrote:
So are static types. Let's get rid of them.
Yes, please.
Sep 29 '08 #12
Matthias Buelow wrote:
It's because many C++ programmers prefer long-winded bureaucracy over
conciseness or even (shock!) simplicity. :)
Some programmers prefer clarity over conciseness. The simplicity of
the code is not changed either way.

I really don't understand the obsession some people (especially
beginners) have about writing code which is as short as possible. Of
course this doesn't mean you should prefer the opposite either, but too
concise == obfuscated.

Do you name all your variables with one single character, and when you
run out of the a-zA-Z characters do you start using to-character
variables? Or do you prefer naming your variables *descriptively*
regardless of how long they become? This is a perfect example where
concise code only leads to obfuscated code which is hard to read and
understand.

When you use the "std::" prefix you are self-documenting the code: You
are telling the reader what kind of function/type that is (a standard
one) and where its definition can be found (in the standard libraries).
For example, if I see this in some random code:

generate(v.begi n(), v.end(), foo);

it's not immediately obvious what this "generate" function is. Is it a
function defined in the same program somewhere? However, if I see this:

std::generate(v .begin(), v.end(), foo);

then there just is absolutely no confusion at all. I *immediately* see
that this is a function from the C++ standard library. Even if I had
never even heard of the "std::gener ate" function, I would still
immediately know where to look for it.

In this case the "std::" prefix made a remarkable difference in
clarity and readability: It made it enormously easier to understand
what's going on (ie. a standard C++ library function is being called,
rather than some program-specific function defined somewhere).

As an added bonus you might avoid name collisions better by leaving
namespaces as they are.
The std:: is just clutter and that's usually bad in a program.
"Just clutter" which makes the code more readable and easier to
understand. Yeah, sure.

I prefer this "clutter" any day over concise code which nobody but the
author can read fluently (and even him only for a couple of weeks after
he wrote it).
Sep 29 '08 #13
Mark Casternoff wrote:
1) using std::cout;
cout << "This is a test";

2) std::cout << "This is a test";
Let me ask you a question: What did you gain in #1 that made it worth
the "using" line?

Did you gain in code clarity? Is #1 clearer code than #2? Would you
have a harder time understanding #2 than #1?

In fact, I would argue that #2 results in clearer and easier to
understand code. I already posted this example in this thread, but let
me repeat it here. If you see this line in a random piece of long code:

generate(v.begi n(), v.end(), foo);

what does that tell you? Is this "generate" function some function
defined elsewhere in the code? Or is it a standard function? Maybe it's
both? How can you know? You can't know unless you examine large amounts
of the program source code or documentation (although some interactive
compilers might make this task easier).

However, assume you instead see this:

std::generate(v .begin(), v.end(), foo);

Now there's absolutely no confusion: "generate" is a function in the
standard C++ library. Even if you have never even heard about this
function, you immediately know where to look for it. You don't have to
try to guess anything.

In this case the "std::" prefix made the code a lot more easier to
understand. Why some people consider this a bad thing is something I
will never understand.
Sep 29 '08 #14
Juha Nieminen wrote:
In this case the "std::" prefix made the code a lot more easier to
understand. Why some people consider this a bad thing is something I
will never understand.
The problem exists on a different abstraction layer. Do you want having
to specially mark everything that isn't in the user program space in
fear of collision? I certainly don't since that turns programs really
ugly for little to no gain.
Sep 29 '08 #15
Matthias Buelow wrote:
Juha Nieminen wrote:
> In this case the "std::" prefix made the code a lot more easier to
understand. Why some people consider this a bad thing is something I
will never understand.

The problem exists on a different abstraction layer. Do you want having
to specially mark everything that isn't in the user program space in
fear of collision? I certainly don't since that turns programs really
ugly for little to no gain.
I never use the "using" keyword to get rid of a namespace, and I have
never found the program becoming "ugly". On the contrary, when you get
used to reading the namespace prefixes, the effect is the opposite: The
program becomes clearer and easier to read.

Exactly what do you find "ugly" in the namespace prefixes? The two ':'
symbols? Come on, please.
Sep 29 '08 #16
Juha Nieminen wrote:
Exactly what do you find "ugly" in the namespace prefixes? The two ':'
symbols? Come on, please.
The entire prefix is visually unappealing (although not really that much
of an eye-catcher in a C++ program) but more important is the fact that
I have to provide more detail than necessary, which is especially
obtrusive in a local context.
Sep 29 '08 #17
Hendrik Schober wrote:
Rolf Magnus wrote:
>[...]
A disadvantage of explicitly qualifying with ::std or even with std is
that it makes it hard to create your own cout and replace all uses of the
standard cout with this one. If you have a

using std::cout;

cout << "Hello world\n";

What about
std::ostream& mine = std::cout;
then?
This allows to redefine 'mine' later and doesn't
need to have 'std::' removed from 'cout'. Or am I missing
something?
That would work, too - if you wrote your whole program with that in mind and
only use libraries where this is done too.

Sep 29 '08 #18
On Sep 29, 6:36*pm, Juha Nieminen <nos...@thanks. invalidwrote:
Mark Casternoff wrote:
1) * using std::cout;
* * * cout << "This is a test";
2) *std::cout << "This is a test";
[...] Why some people consider this a bad thing is something I
will never understand.

Actually, I prefer to be more explicit. Don't assume you (the writer)
or the reader (reviewer) understand the context, that that the
compiler is on your side and that the code is interpreted according to
your intentions.

3) static_cast <void((*static_ cast <::std::ostream & (*)
(::std::ostream &, const char*)(&::std:: operator <<)) (::std::cout,
const_cast <const char*("This is a test")));

Here I explicitly state the full qualified names of any entity. I
explicitly select the operator overload I want. I also always
explicitly state the type of a string literal to foil that evil
implicit const char [] to char* conversion. I also explicitly state
that I am not interested in the the returned value by casting to void.
Don't leave anything to be inferred.

Actually 3) is a little simplified. My code usually is char/w_char
agnostic. So each string literal is further wrapped up in macros. But
I thought I should keep it simple and clear as mud here.

Regards,
Vidar Hasfjord
Sep 29 '08 #19
Matthias Buelow wrote:
Juha Nieminen wrote:
> Exactly what do you find "ugly" in the namespace prefixes? The two ':'
symbols? Come on, please.

The entire prefix is visually unappealing
Yeah, I see how visual beauty is such an important concept in programming.

OTOH some programmers prefer clarity over beauty.
but more important is the fact that
I have to provide more detail than necessary, which is especially
obtrusive in a local context.
Oh, sheesh! Writing self-documenting easy-to-understand code really is
such a PitA. Stupid language standardization committees trying to force
us to write code that someone can actually read and understand.

Do you also make completely uncommented code? Because, you know, it's
way more detail than necessary. And of course you use the 1-character
variable and function names wherever possible, and switch to 2-character
ones when you run out of names (you didn't answer my earlier question on
this, so I have to assume a "yes"). And indentation? Who needs
indentation? That's just a waste of space. Why waste good disk space on
completely unnecessary characters?

I bet you are a huge fan of the IOCCC. Maybe you have participated?
Sep 29 '08 #20

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

19
1501
by: qazmlp | last post by:
I hope comp.lang.c will not find the following question as a complete off-topic. I would like to remove ie.comment out the 'cout' statements during compilation(actually preprocessing) time. The statements like this: cout<<"something\n" ; should be made as
6
21077
by: Omid | last post by:
Hi. I have problems when I try to redirect everything that is sent to cout to a file. I have one piece of code that works and one that does not work. The only difference is which headers I use. What the code does: * First writes "This is sent to prompt" to prompt.
5
4012
by: Mastupristi | last post by:
I want to obtain the c++ equivalent of: unsigned short us = 347; printf("0x%04hX",us); that outputs "0x015B" I ried with: cout.setf(ios_base::hex,ios_base::basefield);
10
3533
by: Gurikar | last post by:
How to make cout not printing on the console. i mean void main() { cout<<"Hello world"<<endl; } Is there any way where i can block printing on console even when iam
7
7579
by: Joe C | last post by:
I'd like to have better control of text output to the console. I'm using Windows and have a little (non-standard) function to help me out: #include <windows.h> void locate(int x, int y ) { COORD cur = { x, y }; SetConsoleCursorPosition( GetStdHandle( STD_OUTPUT_HANDLE ), cur ); }
16
4003
by: mrDumbass | last post by:
#include <iostream> #include <algorithm> #include <string> #include <fstream> using namespace std; /* i would like to keep the numbers of the output : Power , step etc, on the same place in the console. But this isnt going to work with
13
1975
by: Jim Langston | last post by:
I had asked this in comp.lang.c++ with out any answers that would actually work, so I'm hoping someone here may know a way. I am calling C library functions that want to output to stdout. I need to capture this to memory for use internally inside the program without modifying the library calls that actually do the output. This is for the GraphViz libraries and it is the output of dot that I'm actually trying to capture. I have...
1
1273
by: William Chavula | last post by:
void basic() { cout<<"---FOLLOW THESE STEPS TO DIAGNOSE INTERNET PROBLEMS---\n\n"; cout<<"---STEP 1---\n\n"; cout<<"Run your mobile partner software\n\n"; cout<<"---STEP 2---\n\n"; cout<<"Click on TOOLS in the menu bar\n\n"; cout<<"---STEP 3---\n\n"; cout<<"In the tools menu click on PROFILE MANAGEMENT\n\n";
0
11052
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10695
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10379
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7930
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7090
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5956
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4573
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
4172
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3198
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.