Hello world
We will learn through writing code. It is customary start with "Hello world!" program when learning a new programming language. This program simply prints a message in the terminal indicating the code ran successfully.
- C
- C++
src/c/basics/00-hello-world.c
#include <stdio.h>
int main()
{
printf("Hello C!\n");
return 0;
}
src/cpp/basics/00-hello-world.cpp
#include <iostream>
#include <cstdio> // original c standard io to use printf
int main()
{
std::cout << "Hello C++!\n";
// we can still use printf from c standard io
printf("Hello from c standard io printf.\n");
return 0;
}
Compile the code:
# in case of C
gcc filename.c
# in case of C++
g++ filename.cpp
It will produce an executable (binary) file named a.out
. We can run the
executable by typing:
./a.out
If you will to name your program something other than a.out
, you can specify
a custom name using -o
flag:
gcc filename.c -o my_program
tip
- It is possible to include entire standard library in C++ (it is a feature of g++ compiler) by:
#include <bits/stdc++.h>
- Input and output streams can be made more efficient by including following in the beginning of the (main) program:
ios::sync_with_stdio(0);
cin.tie(0);
- Use of newline
\n
is faster thanendl
, becauseendl
always causes a flush operation.