cout
output information; in Mbed we will instead be using printf
or the serial monitor (pc.write
)char
, int
, bool
Variables can be declared, initialized, and assigned
char myChar;
. It reserves space for a character variable myChar
but does not initialize it to any specific value.char myChar = 'H';
=
operator to set a variable to a specific value: myChar = 'H';
Functions can be declared and defined
int addTwoInts (int a, int b);
is an example of a function declaration. Notice how we have not said what the function does besides yet.
A function definition looks like this:
int addTwoInts (int a, int b) {
return a + b;
}
Our compiler reads code from top to bottom, so variables and functions need to be at least declared before they can be used. For convenience, we usually declare variables and functions at the top of files, unless they are declared in special files called header files (we’ll discuss this more in lecture 3).
C++ is not case sensitive or sensitive to white space (unlike python), and the syntax for things like loops or functions is a little different than for MATLAB. Brackets are used to separate different elements of code, and a semi colon ;
is used at the end of most statements.
if (a > b) {
printf("A is greater than B\\n");
}
if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is true
} else {
// block of code to be executed if the condition1 is false and condition2 is false
}
for (statement 1; statement 2; statement 3) {
// code block to be executed
}
Statement 1 is executed (one time) before the execution of the code block.
Statement 2 defines the condition for executing the code block.
Statement 3 is executed (every time) after the code block has been executed.
for (int i = 0; i < 5; i++) {
printf("%d\\n",i);
}
while (condition) {
// code block to be executed
}
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
Comments
//
for comments on a single line or between /*
and */
for a multi-line comment.// Single line comment
/* Multi-line comment
...
... */
Header (.h) files are commonly used alongside files with C++ code (.cpp) files. A header file includes information that would go at the top of your program if the program was in main.cpp
. They are useful for keeping code organized.
What goes in a header file vs. C++ is a matter of convention, not a strict requirement. By convention:
Note that the header / C++ file pairing only applies for C++ files that are outside of main.cpp
; if everything is in one file, you can put whatever would be in a header file at the top of the file (hence the name “header”). Header files also contain special directives to ensure that the declarations in the file are only included once per project (see below). The underscores around the header name are also a convention and not required.
Here’s an example header and C++ setup: