Course Content
C++ Introduction
C++ Introduction
Entry Point of a Program
Every C++ program must have a main()
function. It serves as the entry point of the program. Without a main()
function, the compiler wouldn't know where to start executing the program. It's name is reserved, this means that the function name main()
cannot be changed, and it must follow a specific signature for the program to run correctly.
main
int main() { return 0; }
int main()
: the starting point of a program. It's called the main function, and it's where the program begins executing;{ }
: curly braces define a block of code. Everything inside these braces belongs to the main function and is part of the program's logic;return 0;
: marks the end of the program and indicates that it ran successfully. The 0 means everything went well. If there were issues, this value might be different in the output.
Note
The
return 0;
statement is optional at the end of the main function. If omitted, the compiler will automatically insert it.
Inside the main()
function, you can start writing your code. Every expression should end with a ;
symbol so the program can understand when one command finishes and the next one begins.
main
int main() { 5 + 5; }
Above, you can see a simple expression. Expressions form the building blocks of statements and define how values are calculated or manipulated in a program. The one above doesn't involve variables, built-in commands, or anything complex, but we will use all of these eventually in the future.
main
int main() { 5 + 5; 1 - 8; 9 / 3; }
You can write as many expressions as you want, but each has to end with a ;
. If you remove the semicolon from 5+5;
, C++ will see the expression 5 + 5 1 - 8;
, which will not make sense to it and will generate an error. However, you can write all of your code on a single line if you want.
main
int main() { 5 + 5; 1 - 8; 9 / 3; }
If you run the code above, nothing will appear on the console. This is because C++ might skip the calculation if it determines the result is unused. Moreover, there is no command to display or store the result.
Thanks for your feedback!