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
#include <iostream>
int main() {
std::cout << "Execution starts here" << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#include <iostream>
int main() {
int age = 25;
std::cout << "Age: " << age << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#include <iostream>
int main() {
std::cout << "cout comes from <iostream>" << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#include <iostream>
using namespace std;
int main() {
cout << "No need for std:: prefix now" << endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#include <iostream>
int main() {
std::cout << "Program finished successfully" << std::endl;
return 0; // 0 = success exit code
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 15 topics to unlock
0/15 topics done
Complete these topics first: