473,725 Members | 2,018 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 #1
58 4828
In article <20080928152311 75249-mac@foobarnetor g>, Mark Casternoff
<ma*@foobarnet. orgwrote:
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";
Code written using #1 is more interdependent, since the cout line depends
on there being a using line earlier. On the other hand, it can be more
readable. Use of "using" in source files is mostly a style issue. Use of
#1 in header files is generally a bad idea, especially at global scope;
use #2 in header files unless you have a good reason not to.
Sep 28 '08 #2
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?
I've never heard a good reason why one shouldn't do a "using namespace
std;" at the beginning of every compilation unit. 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.
Sep 28 '08 #3
Mark Casternoff wrote:
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.
#1 for the case you've shown here, but #2 for functions, to give Koenig
lookup a chance. One of Scott Meyer's Effective {C++,STL} books has an
item on this. For longish implementation files, I'll sometimes put a
bunch of

using some_namespace: :some_type;

near the top of the file. There's nothing wrong with using-declarations
("using std::cout;"), but using-directives ("using namespace whatever;")
can lead to weird problems (like potential name clashes whenever a new
name is added to the used namespace), and using-directives at global
scope in header files are just evil.
Sep 29 '08 #4
Stefan Ram wrote:
Mark Casternoff <ma*@foobarnet. orgwrites:
>>1) using std::cout;
cout << "This is a test";
2) std::cout << "This is a test";

I believe the majority of programmers is using style 1.

I prefer style 2, precisely, I prefer:

::std::cout << "alpha";

Reasons:

This code segment has a context-independent meaning
to the maximum extend possible by such a segment:

It can be copied from one source file to another
without the need to copy a using declaration, too.
Well, you need to copy the #includes too.
It can even be copied into

namespace example { namespace std {} void example(){ ... }}

and still retain its meaning.
I've never seen that anyone added his own namespace std somewhere. It would
be quite odd, so I don't see why I should attempt to protect against such a
case.
ISO/IEC 14882:2003(E) is using »::std« once,
»static ::std::locale:: id« in 22.1.1.1.2.p1.
Once isn't really that often. How often does it not use that?

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";

you can simply replace the using declaration and you're done instead of
changing every single occurance of cout in your code.
And yes, I actually had a case where I wanted to exchange std::cout with my
own one. It was a microcontroller device with quite limited resources, so I
wanted to have something that behaves similar to cout, but provides only a
limited subset of the functionality to save resources.

Sep 29 '08 #5
In article <6k************ @mid.dfncis.de> ,
Matthias Buelow <mk*@incubus.de 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?
I've never heard a good reason why one shouldn't do a "using namespace
std;" at the beginning of every compilation unit. 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.
The std:: namespace contains an awful lot of identifiers that use very
simple common words.

If you remove std:: namespace an put everything global, the following
becomes very undesirable since you would have trouble figuring out
which "map"

namespace DoraTheExplorer
{
class map
{
//
};

}
//////////////////
#include "Dora.h"
#include <map>

using namespace std; // or remove std:: altogether
using namespace DoraTheExplorer ;

int main()
{
map theMap; // should this compile or error
// due to missing template arguments?
}
Sep 29 '08 #6
Yannick Tremblay wrote:
using namespace std; // or remove std:: altogether
using namespace DoraTheExplorer ;
....^ here
int main()
{
map theMap; // should this compile or error
// due to missing template arguments?
It should wail about symbol collision...^

Dunno if it does (too lazy^Wbusy to check now), b0rk3d as C++ is, it
probably doesn't.
Sep 29 '08 #7
In article <6k************ @mid.dfncis.de> ,
Matthias Buelow <mk*@incubus.de wrote:
>Yannick Tremblay wrote:
>using namespace std; // or remove std:: altogether
using namespace DoraTheExplorer ;

...^ here
>int main()
{
map theMap; // should this compile or error
// due to missing template arguments?

It should wail about symbol collision...^

Dunno if it does (too lazy^Wbusy to check now), b0rk3d as C++ is, it
probably doesn't.
Either of the three possible outcomes are undesirable.

I like to write my code the way it feels natural. Words like "find"
"sort" "map" "list" "pair", etc are likely to be used. Widening the
range of reserved identifiers/symbols to everything contained in the
C++ standard library steal from me a lot of possible identifiers I
might have liked to use and force me to use less natural words for
these which might make the code less clear, less readable, more bug
prone and harder to maintain. Worse: I might not even know that a
word is reserved by the standard library. I am pretty much able to
remember not to use the C++ reserved keywords (albeit I keep trying to
use "default":-( but pulling the whole standard library in the global
namespace hugely increases the list of reserved words that I am not
allowed to use. I don't want it.

If I write "using namespace std;" at the top of a file, I know that I
am pulling all that in the global namespace but the key is that I
choose to do it. I am perfectly allowed to use "map" for my own
purpose if I don't do "using namespace std;"

So personally, I do not find the std:: namespace a clutter but a very
useful tool.

Yan

Sep 29 '08 #8
Yannick Tremblay wrote:
In article <gb**********@c b.generation-online.de>,
Hendrik Schober <sp******@gmx.d ewrote:
>Yannick Tremblay wrote:
>>[Ridiculous example deleted]
No. The next project introduced its string utilities
in a namespace 'Strings'.

But the point remains that "Strings" is less clear than "StringUtility" .

In this particular case, the loss of clarity is probably acceptable
but that virtual ban on namespaces is IMO a bad thing because I
think it encourages bad naming.
Which ban?
Yannick
Schobi
Sep 29 '08 #9
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?
[...]
Schobi
Sep 29 '08 #10

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
21065
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
4004
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
3503
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
7571
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
3987
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
1962
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
1265
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
8886
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, well explore What is ONU, What Is Router, ONU & Routers main usage, and What is the difference between ONU and Router. Lets take a closer look ! Part I. Meaning of...
0
8750
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9401
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
9104
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...
0
6010
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
4509
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3217
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
2632
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2154
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.