Programming/C++/Syntax
< Programming | C++
Jump to navigation
Jump to search
Note: Common File Extensions:
.cpp
.h
Compiling C++
To run any C++ code, it must first be compiled.
To do this, in terminal, cd to the desired directory and run g++ <path_to_file> -o <name_of_file_to_create>
.
This will generate a new executable file, based on the compiled code.
Run this file via ./<name_of_created_file>
.
Comments
Inline Comments
// This is an inline comment.
Block Comments
/** *This is a block comment. *Comment line 2. *Another block comment line. */
Basic Input and Output
Basic Output
A very basic output example is:
#include <iostream> std::cout << "Hello World!\n";
We can also chain together strings this way:
#include <iostream> std::cout << "Hello " << "World!" << "\n";
If we exclude the \n
, then output will remain on a single line:
#include <iostream> std::cout << "Hello "; std::cout << "World!"; std::cout << "\n";
The above code snippets are all functionally equivalent.
Basic Input
Similar to basic output:
#include <iostream> std::cin >> <variable_here>
For example:
#include <iostream> // This will read in a string as a variable, then immediately display it. string my_string; std::cin >> my_string; std::cout << my_string << "\n";
Variables
Variables are strongly typed in C++. That means you must declare the type as well as the name.
Variable Definition
bool a_bool = true; bool b_bool = false; string my_var_1 = "This is "; string my_var_2 = "a string.";
Variable Usage
#include <iostream> std::cout << "Printing variable values.\n"; std::cout << a_bool << "\n"; std::cout << b_bool << "\n"; std::cout << my_var_1 << my_var_2 << "\n";
Booleans
C++ uses the following bools"
bool true_bool = true; bool false_bool = false;
Null Values
C++ uses the standard null
.
int null_value = null;