Basic Syntax & I/O

Let's kick things off by familiarising ourselves with the basic structure of a C++ program.

Anatomy of a C++ Program

Recall the source code you previously saw:

main.cpp
#include <iostream>

int main() {
    std::cout << "Hello, world!";
    return 0;
}

Breaking it down:

Code
What it does

Brings in the standard I/O library so that we can use things like std::cout

The entry point of every C++ program.

  • int indicates the return type of the function

  • main is the function name.

Prints the text to the console.

πŸ‘‰ You can remember << as pushing the text into the output stream (i.e std::cout in this case)

Recall that int is the return type of the main function.

Hence, at the end of our main function, we should[1] return an int.

You can return anything, really. But usually returning 0 indicates our program has successfully executed.

circle-info

Try augmenting the Hello, world! string to something else like your name!

[1] Your code will still compile even if you don't return anything from the main function. This is because C++ implicilty returns 0 at the end of main(). For more info, refer herearrow-up-right.

Newlines

If you try printing multiple times, you will notice that the output gets concatenated on the same line. You can fix this by adding a newline using std::endl .

Code
Output

Input

It's not quite fun if we hardcode everything into program. Let's augment our program to accept user input externally.

To read input from the user, we can use std::cin >>

circle-info

Note that the direction of the arrows (>>) for std::cin is now reversed compared to <<.

πŸ‘‰ You can remember as data flowing into x.

Namespaces

If you find prefixing std:: before the function calls cumbersome, you can omit it with using namespace std

However, this is generally discouraged in larger projects as it does lead to naming conflicts.

πŸ‘‰ It's usually best practice to be explicit and use std::

Exercise

Build a program that takes in and prints the result of the summation of two numbers.

Last updated

Was this helpful?