Variable declarations define variable's type and optionally initialize them, for example:
double x; int n=5; pp::vector v(5);A function is a block of code within a pair of curly braces, {...}, with a name and a type. The function must return an object of the declared type, unless the type is `void`. A function can optionally take arguments.
For example, here is a function that takes two double arguments and returns a double value,
double multiply(double a, double b) { double r = a*b; /* do some useful stuff */ return r; /* return a value of declared type */ }Here is a function that takes no parameters and returns nothing,
void hello(){ std::cout << "hello" << std::endl; }A function is called by its name followed by the arguments, if any, in parenthesis, for example,
hello(); double x = multiply(2.0, 4.0);
struct
` is `class
` where
everything is public by default; in `class
` everything is
private by default). Functions defined inside a class (called methods)
have direct access to variables declared inside a class. For example,
struct myclass{ double x; void print_x(){std::cout << " x = " << x << std::endl;} }A variable declared with the type "
class_name
" will then
hold an "instance" of the class with its own instances of all variables
and methods.
The things inside an instance of a class are referred to (from outside
of the class) as "variable_name.thing_name
", for example
myclass a,b; a.x=1.0; b.x=2.0; std::cout << "in the instance 'a' of myclass variable x equals " << a.x << std::endl; std::cout << "in the instance 'b' of myclass variable x equals " << b.x << std::endl; a.print_x(); // prints 'x = 1' b.print_x(); // prints 'x = 2'
C++ is a free form language: you can put (multiple) new-lines, spaces, and tabs anywhere between the tokens of the language.
A C++ program is (basically) a collection of functions and
classes/structs. In the top scope of the program there must be declared
a function called `main
`, for example,
int main(){ /* do your stuff here*/ return 0; // if everything went fine }The `
main
` function is called by the operating system when
the program is run.
The return value other than zero signalls the operating system that there was an error during execution.
The `main
` function must be defined according to one of the
following prototypes:
int main() {...} /* no arguments to main */ int main(int argc, char** argv) {...} /* with command-line arguments */ int main(int argc, char* argv[]) {...} /* same as above */The arguments to the `main` function of a program are taken from the command-line that runs the program. For example, the command
./myprogram 1.24 -R:5 z=5 blah-blahprovides the main function of myprogram with the following array of strings as its argument,
{"1.24","-R:5","z=5","blah-blah"}
The main function must return integer zero upon succesful completion, or a non-zero error code.