To better understand the following C++ code, let’s deconstruct it:
Example
#include <iostream>
using namespace std;
int main() {
cout << "Hello GeektoCode!";
return 0;
}
Example explained
If you’re confused about how #include <iostream> and using namespace std work, don’t worry. Consider it merely as a component that (almost) always appears in your program.
- A header file library called #include<iostream> enables us to work with input and output objects like cout . C++ programs gain functionality thanks to header files.
- We can use names for objects and variables from the standard library when namespace std is used.
- Unfilled line. White space is ignored in C++. However, we make use of it to improve code readability.
- The cout object, pronounced “see-out,” is used to output or print text when combined with the insertion operator (). It will display “Hello GeektoCode” in our example.
- The main function is concluded by return 0.
- To actually end the main function, don’t forget to add the closing curly bracket ‘ } ‘.
Remember that, Keep in mind that the compiler ignores blank spaces. The code is more readable when there are several lines, though.
Note: In C++, every sentence is concluded with a semicolon ‘ ; ‘.
Note: The following could also be used to represent the body of the int main() function: int main () { cout “Hello GeektoCode! “; return 0; }
Without of Namespace
Some C++ programs may not require the default namespace library to function. For some objects, the using namespace std line can be skipped in favor of the std keyword followed by the :: (Scope resolution Operator) operator:
Example
#include <iostream>
int main() {
std::cout << "Hello GeektoCode!";
return 0;
}
You can decide whether to use the standard namespace library or not.