C++ is a language, just like English, Latin or Sanskrit. It consists of symbols and grammar, which are used to communicate.
To be a programmer is to be lazy, and to spend your time telling a computer to do things instead of doing them yourself.
Writing a programmer involves understanding what needs to be done, and then conveying those ideas in a way the computer understands.
The purpose of this cheatsheet is to define c++ grammar, and to provide a quick overview of the various concepts of c++.
Sequence:
int x, y, z;
x = y + z
y = 10
z = 15
cout << x;
What do you get?? in class we got 168686842321, which is obviously what 10+15 equals.
The problem is sequence, unlike in mathematics computer where you define simulatenous constraints; in programming operators take place strictly in sequence.
x = y + z -> take the value of y + the value of z and copies them into location x.
Since neither y, z have been assigned, they have random data in them, which added together equals some other large number.
y = 10;
z = 15;
x = y + z;
cout << x;
This is will give you 25
Variables:
a variable is a place where the computer keeps a piece of data.
int x; //defines a variable named x, which is of type int (integer)
x = 5; //copies the value of 5 into location x
cout << x; // prints the value of x to stdout
Variables must be defined before they can be used, when defined they are filled with garbage data -> having essentially a random value.
Variable Types:
type
explanation
how to directly put one in code.
explanation of how to put in code
bool
boolean - true or false
true, false
the words: true, false
int
integer - whole number (can be positive or negative)
1, 12, -53
any whole number
float
floating point number
1.356f, 4.578f
number with a . and an f at the end
double
more precise floating point number (is twice the size)
1.3456, 4.578
number with a .
char
a single character
'a', 'b', 'f', '\n'
' delimited - can only be a single character
character array
a sequence of characters (sudo string)
"hello world"
" delimited - can be any amount of characters
All data is stored as 1's and 0's at the lowest level, type information is needed so that your computer knows what to do with each piece of data
Defining Variables:
Variable definitions tell the computer what variables it will be using inside the current block.
grammar:
type variableName;
examples:
int x;
float y;
double z;
char c;
Variable Names:
Variables can have any name that is of aphanumeric [a-zA-Z0-9] or _'s characters.
However they cannot start with a number.
lhs is a variable name, rhs is something that reduces to a value
List of operators:
=, += , -=. *=, /=, %=
Examples:
x = 5;
x += 10 + 5;
x = y;
x = function1();
Stream based I/O:
I/O stands for input / output, a stream is like an old fashion telegraph line you feed characters into and get characters out of.
Stream I/O is on a technical level a horrible bastardization of c++ grammar, so don't read into it too much.
cout will take whatever you put after the << and feed that to the "standard output" stream, which usually goes to the command console from which you ran the program.
cin:
grammar:
cin >> variableName;
examples:
cin >> x;
cin will read in characters from STDIN, converting those characters appropriate into appropriate data to assign to the variable
Notes:
cin BLOCKS - it will stop the execution of your program until it gets its data
cin statements do not activate until an endl or an EOF is input
Binary Operators:
Math Operators:
+, -, *, /, %
grammar:
lhs operator rhs
examples:
5 + 7
x + y
9 + y
helloWorld + iLikeCheese
Binary operators are when you have two pieces of data / variables with an operator in the middle
These reduce to the most restrictive of their operands -> int / float = int, float / float = float, float / double = float
Comparison Operators:
==, <, >, <=, >=
grammar:
lhs operator rhs
examples:
if( x == 5 ) blah();
if( x < 5 ) blah();
Note: These reduce to bool type data
% - Modulo:
Modulo satisfies the following:
x / y = d
x % y = m
y * d + m = x
The following c++ function is the cleanest way to think of it in my experience
int modulo(int x, int y){ while(x >= y)
x -= y;
return x; }
Reduction:
Computer are fundamentally very simple, and they execute small simple statements one at a time.
Large, complex statements are broken down into small statements and executed one at a time
x = y + z + 15 / 5
While written as a single statement, the computer will reduce it into a series of statements
t1 = 15 / 5
t2 = z + t1
t3 = y + t2
x = t3
you DO NOT know exactly how this is done (right to left taking precedence into account), but it is important to understand that larger statements are broken into smaller individual statements
They are generally broken down from right to left, in order of precedence.
y == z takes place first, then that true/false value is stored in x
and
&&
if( a && b || c)
a && b is checked first
or
||
if( a || b && c)
b && c is checked first
assignment
=, +=, -=, *=, /=, %=
x = y + z
y + z is first, and then that value is assigned to x
Casting:
To convert from one basic data type to another you perform a "cast"
grammar:
(newType) value
There are Issues with precedence that will bite you, so I would HIGHLY recommend this format:
((newType) value)
Always wrapping casts with parenthesis will save you grief
examples:
int x = ((int) 5.5);
float y = ((float) x ) / 10.0;
Notes:
You cannot cast to / from character arrays like this, you have to use functions to get the data you want.
Casting to / from a char will give you its ascii value: int n = ((int) 'c') which has all kinds of uses.
Calling a Function:
A function is a chunk of code that can be called or accessed by name.
For example, sqrt is a square root function that.
Grammar:
functionName ( arg1, arg2, arg3, ...)
Examples:
float sqrtOfX = sqrt(x);
Arguments:
The values that you put within the ()'s are called arguments, they are the data which is passed into the function.
The function will define the number, and type of these that it accepts
Return Type / Value:
Some functions "return" a value, which is the value the function is replaced with during reduction.
sqrt for example returns a float, containing the square root of its argument.
Functions you should know:
There are many useful functions defined in what are called the standard libraries.
#include<math> // includes all the functions defined by the math library
sin(x), cos(x), tan(x), asin(x), acos(x), atan(x): returns the appropriate trig function on x
atan2(x, y): takes the two distances themselves - returning the correct angle without having to check for 3rd quadrant issues - USE IT.
Chris' Helpful Hints:
Indent your code properly
By far the biggest single piece of advice I can give you
Proper indentation will save you HOURS of time, keep every SINGLE line of code properly indented at all times.
Use long and clear variable names
x1 = a + b + c + d + e; is unreadable, and you will have to read through your code many times to fix problems.
Names like boxLength, boxHeight, boxDepth, boxWeight are clear and understandable and you will write better code with them.
Remember the answering the phone analogy, think of what you would say, what you would ask them for, what you would write down, what you would do, what you would say, etc...
Break problems down into the smallest possible piece of work, and do them one at at time
When your code doesn't work, go through it one line at at time and justify what EACH line of code does
If you dont know what it does take it out.
Conditionals
Conditionals allow for code to be executed - sometimes
If:
Allows for code to be executed if a conditon is met
grammar:
if (condition1) {
doSomething1();
} else if (condition2) { doSomething2();
} else if (condition3) {
doSomething3();
} else {
doSomething4();
}
You can put a single statement after an if without {}'s, but it will bite you so I recommend against it.
You can have as many else if statements as you like.
Only one else is allowed, and it must be at the end.
examples:
if(x < 5) {
cout << "x is less then 5";
}
if(x != 10 && y < 5){
cout << "blah";
} else if ( x != 10 && y < 10) { cout << "y is between 5 and 10"; } else { cout << "x is not 10, or y is >= 10"; }
Switch:
Switch is more there because it can be implemented effeciently then because it is useful.
It can however be used to clean up ugly if chains.
grammar:
switch(variable) {
case (value1):
doSomething1();
break;
case (value2):
doSomething2();
break;
default:
doSomething3();
break;
}
table = {value1: label0, value2: label1, default: label2}
goto table[value]
label0:
doSomething1()
goto end
label1:
doSomething2()
goto end
label2:
doSomething3()
goto end
end:
Which can be a significant performance improvement in many cases, but it shouldn't really matter for you guys - use if unless they force you to use switch.
Functions:
A function is just some block of code, that does something.
The question is, if you had a generic block of code that did some work, what information would you need to be able to use it?
Firstly you need a name, some unique identifier to refer to this function - such as pow.
Then you would need to know what values the function needs to work, and what value it returns - the function prototype.
Finally, someone somewhere needs to write the actual code that takes those values, does the work, and returns some value.
The fundamenting attitude to remember with functions is - I dont care, I don't want to know.
They are defined so that the caller, needs to know as little about the callee as possible.
Calling a function:
grammar:
functionName(param1, param2, param3, ...)
Example:
pow(5, 3)
Often times functions return a value, which is a single variable that the function becomes when executed.
int x = pow(3, 5) // pow returns the value 243, which can then be assigned to x
Defining a function prototype:
A function prototype, says that there is a function called this, which does this - It is just declaring the existence of a function, not the actual code inside the function. Generally these are done at the top of your code file, so that they are known before the rest is parsed.
int factorial(int x); //defines a function named factorial, which takes a single integer, and returns a single integer
Defining a function:
This actually assigns the code associated with a function, it can be defined anywhere, even in other functions so long as it is linked into the final executable - actually dll's or dynamically linked libraries allow functions to be defined in external libraries which are linked at run-time.
//main is just a function, albiet with a special name that is where execution starts
int main(int argc, char** argv){
...
}
// a simple recursive function (recursive - calls itself)
int factorial(int value){
if(value == 0 || value == 1){
return 1;
} else {
return factorial(value-1) * value;
}
}