Error: 'cout' : undeclared identifier; though I've included iostream header file in program
Asked Answered
I

2

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.

Irina answered 22/1, 2014 at 6:58 Comment(5)
Use std::cout instead of cout only. Append std:: before everything you use from namespace std.Contraindicate
Or in a case like this - when you write a very simple program, you can always write using namespace std; somewhere below your #include <iostream>. 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.Meris
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.Padraig
There is more on the using namespace std issue here: #1453221Padraig
Possible duplicate of error C2065: 'cout' : undeclared identifierEzarras
D
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

Dorita answered 22/1, 2014 at 7:11 Comment(4)
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::<whatever>. It tells me that <whatever> is from the standard library.Holzer
@Mona std::cout is part of the C++ standard library and so not available in C codeDorita
@DavidHammen please could you clarify - what is dubious about std::cout and what do you prefer?Cathcart
@DavidHammen Apologies - there was too much sun on my screen and I saw "using std::cout is dubious" as "using std::cout is dubious"!Cathcart
L
2

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

Loot answered 22/1, 2014 at 7:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.