Programming/C++/Syntax
< Programming | C++
Jump to navigation
Jump to search
Note: Common File Extensions:
.cpp
.h
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;
Import Statements
If Statements
Basic If
if (x == y) { # Logic if true. }
Full If
if (x == y) { # Logic if true. } else if (! x && (y || z)) { # Logic for "else if" true. } else { # Logic for false. }
Switch/Case Statements
switch (<conditional_statement) { case <result_1>: # Logic if matches <result_1>. break; case <result_2>: # Logic if matches <result_2>. break; ... default: # Default/fallback if no matched results. break; }
Note that the break statements are optional, but recommended. Removing a break statement will make the code execute into the next result section, instead of exiting the switch block.
Loops
For Loop
for (<counter_var> = <start_index>; <end_condition>; <counter_var_modifier>) { # Loop logic here. }
Ex:
for (int index = 0; index < 10; index++ { # Loop logic here. }
While Loop
while (<condition>) { # Loop logic here. }
Functions
<return_type> <function_name>(<arg1>, <arg2>, ..., <argn>) { # Function logic here. return <return_value>; }
Ex:
# This is a function that returns nothing. void my_function() { # Function logic here. }
# This is a function that returns an int. int my_function() { # Function logic here. ... int my_return_int = 5;
... return my_return_int; }
# This is a function that returns nothing, but takes three parameters. void my_function(int my_int, std::string my_string, bool some_other_arg) { # Function logic here. }