abcd
abcd

Reputation: 111

What's wrong with this C++ program?

When I compile this program:

#include<iostream>

using namespace std; 

std::cout<<"before main"<<endl;

int main()  
{

}

...I see this error from the compiler:

error: expected constructor, destructor, or type conversion before '<<' token

Please help me understand what this means and what's wrong with my program?

Upvotes: 11

Views: 10418

Answers (5)

Mekanic
Mekanic

Reputation: 199

The above answers are correct but just to add. If you already have:

#include<iostream>
using namespace std;

You dont a have to type:

std::cout<<"before main"<<endl;

You can just type:

cout<<"before main"<<endl;

Because you already declared that your using namespace std; can save you a little typing. Cheers!

Upvotes: 0

log0
log0

Reputation: 10917

you cannot write

std::cout<<"before main"<<endl;

outside a function.

-- edit --
The single entry point of a c++ program is the main function. The only thing that may occur before the execution of the main function is the initialization of static/global variables.

static int i = print_before_main_and_return_an_int();

Upvotes: 7

razlebe
razlebe

Reputation: 7144

You're seeing that error because your

std::cout<<"before main"<<endl;

statement needs to be within the scope of your main() function (or some other function) in order for this program to be valid:

int main()
{
   std::cout<<"before main"<<endl;
}

Unrelated to your specific question, one extra point: as you are using namespace std, the explicit std:: on std::cout is redundant.

Upvotes: 15

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361254

Statements cannot be executed outside functions.

However, if you make that expression which is used to initialize a global variable, then that will be okay in the sense that compiler will not give any error or warning.

For example, the following code will print what you want to print:

#include <iostream>

std::ostream &gout = std::cout<<"before main"<< std::endl;

int main() { }

Output:

before main

Online demo : http://www.ideone.com/Hz4qu


Here I do almost the same thing as done in this topic:

Is main() really start of a C++ program?

Upvotes: 7

Eric Z
Eric Z

Reputation: 14505

You have to define the line inside a function.

std::cout<<"before main"<<endl;

Upvotes: 3

Related Questions