Introduction to C++ Programming

October 27, 2018 | 1 Tags | 0 Comment

Introduction to C++ Programming

A C++ Program always starts executing in a special function called main() function. Let’s take a look at a simple C++ code that would print the words “This is a simple C++ program!”

#include <iostream>

int main() {
   std::cout << "This is a simple C++ program!\n";

   return 0;
}

#include <iostream> is a preprocessing directive. It adds some predefined source code to our existing source code before the compiler begins to process it. iostream is a library, a collection precompiled C++ code that C++ programs can use.

int main() is the main function where program execution begins.

std::cout << "This is a simple C++ program!\n"; causes the message “This is a simple C++ program!\n” to be displayed on the screen.

return 0; terminates main() function and causes it to return the value 0 to the calling process.

There is an alternative way of writing above program:

#include <iostream>

using std::cout;

int main() {
   cout << "This is a simple C++ program!\n";

   return 0;
}

The using directive allows us to use a shorter name for the std::cout printing object. The name std stands for “standard”, and the std prefix indicates that cout is part of a collection of names called the standard namespace. The std namespace holds names for all the standard C++ types and functions that must be available to all standard-conforming C++ development environments.

Another way to use the shorter name for cout within a C++ program

#include <iostream>

using namespace std;

int main() {
   cout << "This is a simple C++ program!\n";

   return 0;
}
Compile and Execute C++ Program in Linux

Open a text editor, copy and paste the above code. Save the file as simple.cpp. Open a command prompt and go to the directory where you’ve saved the file.

If you’re using gcc compiler, you type g++ simple.cpp and press enter to compile your code. If there are no errors in your code, it would generate a.out executable file. Now, type a.out to execute your program and you will see the output “This is a simple C++ program!”.

$ g++ simple.cpp
$ ./a.out
This is a simple C++ program!
C++
Samuel Yang image
Samuel Yang

If you like this tutorial, you can support me

Donate Now