Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's wrong with this C++ program?

Tags:

c++

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?

like image 374
abcd Avatar asked May 04 '11 09:05

abcd


People also ask

What is the error in the C program?

There are 5 different types of errors in C programming language: Syntax error, Run Time error, Logical error, Semantic error, and Linker error. Syntax errors, linker errors, and semantic errors can be identified by the compiler during compilation.

Why is C so unsafe?

C and C++ are unsafe in a strong sense: executing an erroneous operation causes the entire program to be meaningless, as opposed to just the erroneous operation having an unpredictable result. In these languages erroneous operations are said to have undefined behavior.

Why C programming is not used?

The operating systems are written in C. Originally Answered: Why is C programming language not used for smartphones and other hardware devices instead of Java? Mostly because smartphones focus a lot on visual things and Standard C does not have a standard Graphics library.

What is logical error in C?

Logical Errors : On compilation and execution of a program, desired output is not obtained when certain input values are given. These types of errors which provide incorrect output but appears to be error free are called logical errors.


2 Answers

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();
like image 169
log0 Avatar answered Oct 05 '22 11:10

log0


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.

like image 37
razlebe Avatar answered Oct 05 '22 10:10

razlebe