basic lang syntax - sluczak/cpp_by_example GitHub Wiki
Examples for this part available on git after calling the command:
git checkout -b origin simple
Areas in code which are being ignored by compiler
//
is interpreted as single line comment. All characters after this sequence will be ignored by compiler
// this is a one-liner comment
/*
and */
are the multi-line comment delimiters.
All characters between those two sequences are ignored by compiler.
/*
this is a multi-line
comment
*/
This application will have absolutely no result, but will compile and run
int main()
{
return 0;
}
main
is the name which is required for a runnable function in C++ project. There may be only one function with this name.
main()
function has to return integer (int
) value.
Function body is limited with
{
and}
(bracket) characters.
Each line of function body has to be end by
;
(semicolon) character.
return 0;
means that this function returns integer of value0
.
In order to gain access to additional functions, that are specified in different libraries and/or header files, you can explicitly include those files by writing #include
precompiler instructions on the top of source code file.
As shown on example below, there are two variants of #include
:
-
<
and>
(angle brackets) version - is used to include Standard Template Libraries (STL). STLs are the libraries defined by C++ standard. They contain many useful functions, templates and classes, which may be useful in your everyday work. -
"
and"
(quotation marks) version - is used to include source code header files. It requires the relative path to header path and proper extension .h.
#include <iostream> //STL library
#include <algorithm> //STL library
#include "headerFile.h" //header file
#include "subfolder/otherHeaderFile.h" //header file in subfolder
int main()
{
std::cout << "Hello World" << std::endl; //usage of <iostream> library features
return 0;
}
visible above
std::cout
will be introduced in next chapters
Code in C++ is organized with use of {
and }
brackets. Area between opening and closing bracket is called a "scope".
Scope delimits the area of variable, classes and functions.
The overal rule is that if something is declared within some scope, it is usable inside of this scope, and not usable outside of it.
Scopes can be nested.
int main() { // this is a begining of main() fuction scope
int a = 2; // a is declared in whole main() function
{ // this is a nested scope. It could be a 'for' loop or anything else
a = 4; // a is accessible, because it was declared in parent scope
int b = 2; // b is declared only in sub scope
}
std::cout << a; // prints a = 4
std::count << b; // this won't compile!! b was not declared in this scope
return 0;
}