Explaining our first C++ program
In this part, I will explain the program foo.cpp that we created in the first part of the program.
Code: Select all
#include <iostream>
using namespace std;
int main()
{
cout<<"Hello World!!!"<<endl;
return 0;
}
I will try to keep this part simple so I won't go all uber geek on you.
Code: Select all
#include <iostream>The io in iostream means input / output, so this include directive is essential if you want to display some text on the screen / get some input from the keyboard.
The next line:
Code: Select all
using namespace std;Let me give you an example:
If I didn't include
Code: Select all
using namespace std;Code: Select all
#include <iostream>
int main()
{
std::cout<<"Hello World!!!"<<std::endl;
return 0;
}
The next line is:
Code: Select all
int main()So as you can see we are declaring a function called int main() and it has no arguments inside the parenthesis and it returns an int.
The int in the int main() means integer, and if you don't know a integer is, it's a whole number (no decimals).
The reason the main() function is a int is because we have to return a value at the end of the function.
The main() is a very special function in which it is the function where everything in it is executed and only it executed.
The main() function is a MUST!!!
If there is no main, the program will have to execute thus giving us an error.
Code: Select all
{Code: Select all
cout<<"Hello world!!!"<<endl;Now, cout is a way to print out a character string to standard output.
A character string is surrounded by double quotes ("") in C++/C.
Another cool thing about it is that it accepts formatting which are special characters used to format the look or the presentation of the text.
endl is a way of saying "newline" and that is also flushes the buffer (writes unwritten character in the buffer to the output).
You can achieve a newline by writing '\n', but because endl flushes the buffer it's best to use endl then '\n'.
Now, if you look closely you can see a ;, this indicates to the C++ compiler that the line of code is finished, so DON'T FORGET IT!!!
Otherwise it will give you a bunch of errors.
**For windows users, Linux users please skip.
Code: Select all
cin.get();Code: Select all
return 0;This ends our program, giving the value from return to the OS. On POSIX machines 0 means the program has ended with no problems, while returning the value of 1 means that the program has ended with errors.
***Note: In C++ you dont actully need a return 0; the compiler adds the return 0; if there is none found.
}
This means that the function has ended.
Now, deep breath in, deep breath out.
Was that so hard ?
<<Prev | Next>>
Advertising

