← Back to C++ Course | Chapter 1: Introduction & Basics | Lesson 4 of 15

C++ First Program

The Main Function

Every C++ program needs exactly one main() function, because that's the function the operating system calls to start your program running. Execution always begins at the first line inside main() and continues from there, regardless of where other functions are defined in the file.

Example: The Main Function

cpp
#include <iostream>

int main() {
	std::cout << "Execution starts here" << std::endl;
	return 0;
}

Printing Output

cout, short for 'character output', sends data to the console using the << stream insertion operator, which you can chain to print multiple values in one statement like cout << "Age: " << age. Think of << as an arrow pushing data into the output stream, one piece at a time.

Example: Printing Output

cpp
#include <iostream>

int main() {
	int age = 25;
	std::cout << "Age: " << age << std::endl;
	return 0;
}

Header Files

Header files declare functionality that isn't built into the core language itself, so you have to explicitly pull them in with #include. <iostream> specifically declares cout, cin, and the other stream objects — without including it, the compiler wouldn't recognize cout at all.

Example: Header Files

cpp
#include <iostream>

int main() {
	std::cout << "cout comes from <iostream>" << std::endl;
	return 0;
}

Standard Namespace

The std namespace groups together every name the standard library defines, which prevents naming collisions with your own code. Writing using namespace std; lets you write cout instead of the fully qualified std::cout, though larger projects often skip this and write std:: explicitly to avoid ambiguity.

Example: Standard Namespace

cpp
#include <iostream>
using namespace std;

int main() {
	cout << "No need for std:: prefix now" << endl;
	return 0;
}

Returning Zero

return 0; at the end of main() isn't just a formality — it's the exit code the operating system receives, and by convention 0 means the program finished successfully. Returning a nonzero value instead signals that something went wrong, which shell scripts and other programs can check for.

Example: Returning Zero

cpp
#include <iostream>

int main() {
	std::cout << "Program finished successfully" << std::endl;
	return 0; // 0 = success exit code
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.