C++ Fundamentals
The C++ concepts you need to use the VEXLearn template and write VEX software: data types, syntax, loops, functions, header files, and namespaces.
Data Types and Their Purpose
A data type defines what kind of data a variable can hold. Here are the data types used in the VEXLearn template:
| Data Type | Purpose | Examples |
|---|---|---|
int |
Holds a whole integer value | 1, 2, -5, 98729 |
double |
Holds a number with decimals | 2.2, 5.7, 1.0, 98794.48 |
bool |
Holds a true or false value | true, false |
string |
Holds text | "Hello!", "Coding is fun" |
void |
Used in function return types (holds no value) | None |
enum |
A custom-defined data type | MENU, Hello123, John |
These aren't all C++ data types, just the ones primarily used in the template.
Basic Syntax
General Syntax
Almost everything in C++ ends with a semicolon (;), just like a period ends a sentence. The exceptions are for loops, while loops, and if-statements, which don't need one.
The compiler reads your code from line 1 to the end. If you call a variable or function before it's been defined, you'll get an error. Header files help solve this problem.
Initializing Variables and Assigning Values
Variables are always initialized like this:
// Declare a variable (just reserves the name and type)
data_type variable_name;
// Declare AND assign a value at the same time
data_type variable_name = value;
Examples of declaring and initializing variables:
int age = 25;
bool sleeping = true;
double average = 8.8;
string greeting = "Hello!";
Assigning a new value to an already-declared variable (no datatype prefix needed):
age = 30;
sleeping = false;
average = 9.1;
greeting = "Goodbye!";
Mathematical, Assignment, Comparison, and Logical Operators
| Operator | Purpose | Examples |
|---|---|---|
| + | Adds two values | 5 + 2, speed1 + speed2 |
| - | Subtracts two values | 5 - 2, speed1 - speed2 |
| / | Divides two values | 5 / 2, speed1 / speed2 |
| * | Multiplies two values | 5 * 2, speed1 * speed2 |
| % | Remainder after division (integers only) | 5 % 2 -> 1 |
| ++ | Increases value by 1 | speed1++ -> speed1 + 1 |
| -- | Decreases value by 1 | speed1-- -> speed1 - 1 |
| Operator | Purpose | Examples |
|---|---|---|
| = | Assigns a value | int dogs = 3 |
| += | Adds then assigns | x += 3 -> x = x + 3 |
| -= | Subtracts then assigns | x -= 3 -> x = x - 3 |
| /= | Divides then assigns | x /= 3 -> x = x / 3 |
| *= | Multiplies then assigns | x *= 3 -> x = x * 3 |
| Operator | Purpose | Examples |
|---|---|---|
| == | Equal to | 5 == 5 -> true |
| != | Not equal to | 5 != 3 -> true |
| > | Greater than | 5 > 3 -> true |
| < | Less than | 3 < 5 -> true |
| >= | Greater than or equal to | 5 >= 5 -> true |
| <= | Less than or equal to | 3 <= 5 -> true |
| Operator | Purpose | Examples |
|---|---|---|
| && | True if BOTH sides are true | true && true -> true false && true -> false |
| || | True if EITHER side is true | false || true -> true false || false -> false |
| ! | Inverts (NOT) | !false -> true !true -> false |
While Loops, For Loops, and If-Statements
These control structures let you run code repeatedly or conditionally.
While Loop
Repeats as long as the condition is true:
while (statement) {
// runs repeatedly while statement is true
}
// Runs forever (common in VEX driver control loops)
while (true) {
// something
}
// Real example
while (dogs >= 3) {
// something
}
while (pistonsAreActivated) {
// something
}
For Loop
Runs a set number of times with an index variable:
// Basic structure: initialize ; condition ; increment
for (int i = 0; i < value; i++) {
// runs while i < value, then i increases by 1 each time
}
// Real example - ramp speed from 10 down to 1
for (int speed = 10; speed > 0; speed--) {
// something
}
If-Statement
Only runs if the condition is true:
if (condition) {
// runs only when condition is true
}
// Example
if (pistonsAreActivated == false) {
pistonsAreActivated = true;
}
// Compact form
if (speedNow > 6) { speedNow = 6; }
Ternary Operator
A compact if-statement for assigning values:
// variable = (condition) ? valueIfTrue : valueIfFalse;
int speed = (turboMode) ? 12 : 6;
You can always replace a ternary operator with a regular if-statement. Ternaries are more concise but less beginner-friendly.
Enumerators (enum)
An enum is a custom datatype you define. It's used in display.cpp for screen states. You can avoid it unless you specifically need it.
// Define an enum
enum ScreenState { MENU, MOTORS, BATTERY, TEAM, SOFTWARE };
// Use it like any other datatype
ScreenState currentScreen = MENU;
// Change it
currentScreen = MOTORS;
Program Structure
A program can be split into many files that work together. In VEXLearn, you'll see .cpp source files and .h header files.
Header Files
A header file (.h) contains declarations: it tells other files what exists. The .cpp file contains the actual implementation. Think of the header as a table of contents.
#pragma once // Prevents duplicate inclusion errors
// Only declare functions that other files need to call
void move(double distance, double heading, double volt_max);
void turn(double target_heading, double volt_max);
Always start header files with #pragma once. Without it, including the same header multiple times causes "multiple definition" errors in larger projects.
To declare a function in a header, copy the function signature from the .cpp file, remove the opening {, and add a semicolon:
// In movement.cpp - full implementation:
void move(double distance, double heading, double volt_max) {
// ... implementation ...
}
// In movement.h - just the declaration:
void move(double distance, double heading, double volt_max);
File Integration Through #include
Use #include to bring functions from another file into the current one:
// Include your own header files (use quotes)
#include "movement.h"
#include "vex.h"
// System/library headers use angle brackets
#include <cmath>
Creating and Calling Functions
Functions are reusable blocks of code. Here's the format:
// Create a function
return_type function_name(arguments) {
// body
}
// Example - returns an int
int getSum(int a, int b) {
int c = a + b;
return c;
}
// Most VEX functions return void (nothing)
void activatePiston() {
Piston.set(true);
}
// Functions can have default argument values
int getSum(int a = 1, int b = 1) {
return a + b;
}
// getSum() -> returns 2 (uses defaults)
// getSum(3,4) -> returns 7
Calling a function:
// Call and discard result
activatePiston();
// Call and store result
int sum = getSum(6, 7); // sum = 13
// Functions can call other functions
int getSumOfFour(int a, int b, int c, int d) {
int ab = getSum(a, b);
int cd = getSum(c, d);
return getSum(ab, cd);
}
Namespaces
A namespace is a named scope that groups related functions, based on which library a function comes from. Without a namespace declaration, you'd need to write the full path every time:
// Full form - specifying the namespace explicitly
vex::wait(1, sec);
// Add this line once at the top of your file:
using namespace vex;
// Now you can write the short form everywhere
wait(1, sec);
In VEXLearn, using namespace vex; is already included in the template files, so you can call VEX functions directly without the vex:: prefix.
Practice: Trace a C++ function
double wheelTravel(double circumference, double turns) {
return circumference * turns;
}Worked example. wheelTravel(20.0, 2.0) returns 40.0. Each turn of a wheel with a 20 cm circumference covers 20 cm when there is no slip.
Your turn. What does wheelTravel(20.0, 3.5) return? Which argument tells the function how many times the wheel turns?
Reveal the answer
It returns 70.0 cm. The second argument, 3.5, is assigned to turns.