Syntax of C++
Now I hope you know the meaning of the word Syntax; it means a structure or a way of writing a programming language in the context of programming. Now let’s learn the Syntax of C++. I have written some code below so we break each line and understand its purpose ok.
#include <iostream> using namespace std; int main() { cout << "Hello World!"; return 0; }
Example explained of Syntax of C++
Line #1: #include <iostream>
is a header file library that lets us work with input and output objects, such as cout
(used in line 5). Header files add functionality to C++ programs.
Line #2: using namespace std
means that we can use the standard library’s names for objects and variables.
Note: Don’t worry or hesitate if you don’t understand how #include <iostream>
and using namespace std
works. Just think of it as something that (almost) always appears in your program and is a necessary part of our program; without it, we face an error ok.
Line #3: A blank line means C++ ignores white space. But we use it to make the code/source code more readable & understandable.
Line #4: Another thing that always appears in a C++ program is int main(). This is called a function or method, or you can say behavior. Any code inside its curly brackets {} will be executed.
Line #5: cout (pronounced as “see-out”) is an object used together with the insertion operator (<<) to output/print text. In our example, it will output “Hello World!”.
Note: Every C++ statement ends with a semicolon ( ;).It is also called terminator because it terminates our statement or line of code; I hope you got it.
Note: The body of int main() could also be written as:
int main () { cout << "Hello World! "; return 0; }
Remember: The compiler ignores white spaces. However, multiple lines make the code more readable & understandable.
Line 6: return 0 ends the main function.
Line 7: Do not forget to add the closing curly bracket } to end the main function; otherwise, you will get an error.
Omitting Namespace in C++
You might see some C++ programs that run without the standard namespace library. The using namespace std line can be omitted and replaced with the std keyword, followed by the (::) operator for some objects:
For example:
#include <iostream> int main() { std::cout << "Hello World!"; return 0; }
NOTE: It is up to you whether you want to include the standard namespace library.
Link: https://Codelikechamp.com
Medium Link: Follow me on Medium
Linkedin Link: Follow me on Linkedin