cout vs std::cout

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Mark Casternoff

    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.

  • blargg

    #2
    Re: cout vs std::cout

    In article <20080928152311 75249-mac@foobarnetor g>, Mark Casternoff
    <mac@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.

    Comment

    • Matthias Buelow

      #3
      Re: cout vs std::cout

      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.

      Comment

      • Jeff Schwab

        #4
        Re: cout vs std::cout

        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.

        Comment

        • Rolf Magnus

          #5
          Re: cout vs std::cout

          Stefan Ram wrote:
          Mark Casternoff <mac@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.

          Comment

          • Yannick Tremblay

            #6
            Re: cout vs std::cout

            In article <6ka9p5F6fbcoU1 @mid.dfncis.de> ,
            Matthias Buelow <mkb@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?
            }


            Comment

            • Matthias Buelow

              #7
              Re: cout vs std::cout

              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.

              Comment

              • Yannick Tremblay

                #8
                Re: cout vs std::cout

                In article <6kc939F76g72U1 @mid.dfncis.de> ,
                Matthias Buelow <mkb@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



                Comment

                • Hendrik Schober

                  #9
                  Re: cout vs std::cout

                  Yannick Tremblay wrote:
                  In article <gbqqk9$v30$1@c b.generation-online.de>,
                  Hendrik Schober <spamtrap@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

                  Comment

                  • Hendrik Schober

                    #10
                    Re: cout vs std::cout

                    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

                    Comment

                    • Hendrik Schober

                      #11
                      Re: cout vs std::cout

                      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

                      Comment

                      • Matthias Buelow

                        #12
                        Re: cout vs std::cout

                        Hendrik Schober wrote:
                        So are static types. Let's get rid of them.
                        Yes, please.

                        Comment

                        • Juha Nieminen

                          #13
                          Re: cout vs std::cout

                          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).

                          Comment

                          • Juha Nieminen

                            #14
                            Re: cout vs std::cout

                            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.

                            Comment

                            • Matthias Buelow

                              #15
                              Re: cout vs std::cout

                              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.

                              Comment

                              Working...