16

I am trying to compile the simple program below. But, it's not compiling & gives error:

error C2065: 'cout' : undeclared identifier

I want to ask you that why this program doesn't work though I've included iostream header file in it?

#include <iostream>

void function(int) { cout << “function(int) called” << endl; }
void function(unsigned int) { cout << “function(unsigned int) called” << endl; }
    int main()
    {
        function(-2);
        function(4);
        return 0;
    }

Thanks in advance.

yuvi
  • 1,032
  • 1
  • 12
  • 22
  • 8
    Use `std::cout` instead of `cout` only. Append `std::` before everything you use from `namespace std`. – sgarizvi Jan 22 '14 at 06:59
  • Or in a case like this - when you write a very simple program, you can always write `using namespace std;` somewhere below your `#include `. It will inform the compiler to look for `cout` in std namespace, thus allowing your `cout` to work. Although this is considered a bad practice whatsoever. – Mateusz Kołodziejski Jan 22 '14 at 07:03
  • 3
    Avoid `using namespace std;`. That is guaranteed to bite you one day. If you don't want to type `std::cout`, use `using std::cout`, but limit it to a small scope, and don't use it in headers. – juanchopanza Jan 22 '14 at 07:06
  • There is more on the `using namespace std` issue here: http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice – juanchopanza Jan 22 '14 at 07:20
  • Possible duplicate of [error C2065: 'cout' : undeclared identifier](https://stackoverflow.com/q/1868603/608639) – jww Sep 24 '18 at 03:28

2 Answers2

21

The cout stream is defined in the std namespace. So to name it you write:

std::cout

If you want to shorten this to cout then you can write

using namespace std;

or

using std::cout;

before writing cout.

Any good documentation source will tell you which namespace contains an object. For instance: http://en.cppreference.com/w/cpp/io/cout

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
  • 1
    Side comment: Don't use `using namespace std`. If you use this atrocity in a header, users of that header will come for your head. The consequences are less severe if you use this in a source file. Reviewers of that file will regard the author as a hopeless newb. Even `using std::cout` is dubious. I, for one, like to see that `std::`. It tells me that `` is from the standard library. – David Hammen Jan 22 '14 at 08:23
  • @Mona std::cout is part of the C++ standard library and so not available in C code – David Heffernan Oct 25 '16 at 06:21
  • @DavidHammen please could you clarify - what is dubious about `std::cout` and what do you prefer? – drkvogel Apr 26 '17 at 10:35
  • @DavidHammen Apologies - there was too much sun on my screen and I saw "`using std::cout` is dubious" as "using `std::cout` is dubious"! – drkvogel Apr 26 '17 at 10:37
2

You have to write std::cout or add using std;

Uri Y
  • 840
  • 5
  • 13