Here is the hello world program for C++:
#include <iostream>
int main()
{
std::cout << "Hello, World" << std::endl;
return 0;
}
Building a C++ program is a three step process:
- Code is run through preprocessor which processes meta information
- The code is compiled where each .cpp file is translated to .o object file
- Individual object files are linked together into a single application.
Main function
Main function is where program execution starts. It comes in two flavors: with and without arguments. With arguments, it looks as follows:
int main(int argc, char* argv[])
where argc
gives the number of commandline arguments to the program, and argv
array contains those arguments. The actual arguments start from index 1.
cout
is the stream for standard output, cerr
is the stream for standard error. The <<
operator lets one add data to the stream. The std::cin
input stream
obtains input from the user. Here is an example:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string name;
cout << "Enter your name"
cin >> name;
}
Namespaces are used to address the problem of naming conflicts between different pieces of code. For example a third party library might have a symbol that conflicts with a name you have defined. You can place your code in a separate namespace to avoid a naming conflict.
namespace myspecialcode {
void doit();
}
Use the scope resolution operator ::
to specify the namespace such as myspecialcode::foo();
. A using
declaration can be used to refer to an item within a namespace. For example, using std::cout
.
Literals are used to write numbers or strings in your C++ code. Examples are as follows
- Decimal 123
- Octal 0123
- Hexadecimal 0x137
- Binary 0b1010001
- Float 3.14f
- Double 3.14
- Character 'A'
- zero/null terminated array of characters "string array"
Variables have to be declared before they can be used. They can be declared and defined in the same statement. Some of the common variable types in C++ are as follows:
- int, unsigned int (usually 4 bytes)
- short (usually 2 bytes)
- long (usually 4 bytes)
- long long (usually 8 bytes)
- float (usually 4 bytes)
- double (usually 8 bytes)
- char (1 byte)
- bool (true/false)
There is no primitive string type. However the Standard Library provides the std::string
type which can be used and provides safety over C-style character arrays.
C-style and C++ style casts
float myFloat = 1.16f;
int one = (int) myFloat;
int two = int(myFloat);
C++ style casts:
int three = static_cast<int>(myFloat);
Sometimes variables can be automatically cast or coerced. Example: short can be coerced to a long because long represents a data type with atleast the same precision.
Enumerated types can be used to represent an enumerated list of values. Although the underyling value is stored as an integer, the compiler can give a warning if arithmetic is attempted.
Example:
enum Color {Red = 1 , Green, Blue};
Using enums:
Color color = Color::Red;
Structs let you bundle one or more pieces of information into a new type. An example is storing information about a person. The struct representation might be as follows:
struct Person {
std::string FirstName;
std::string LastName;
int personNumber;
std::string Address;
};
}
The individual pieces of the struct can be accessed using the .
operator. Here is an example:
#include <iostream>
using namespace std;
int main()
{
Person person;
person.FirstName = "Jack";
person.LastName = "Sparrow";
person.personNumber = 1;
person.Address = "Caribbean";
cout << "Person's name is " << person.FirstName << person.LastName << endl;
cout << "Person's address is " << person.Address << endl;
return 0;
}
If the condition inside the if
statement is true, then the following line or block of code is executed. Otherwise, execution continues with the else
case if it is present, or with the following code.
Switch statements are an alternative to cascading if/else statements. However, the expression being switched must either be an integral type, an enumerated type, or a strongly enumerated type and be able to compared to constants. Example:
switch (color) {
case Color::Red:
cout << "Red was chosen" << endl;
break;
case Color::Green:
cout << "Green was chosen" << endl;
default:
cout << "Unsupported color was chosen" <<endl;
}
Switch statements have fallthrough behavior, so one must be cautious and insert break
statements when the logic for a particular condition ends.
There is a single ternary operator which is essentially a short hand for a simple if/else statement:
std::cout << (num > 4) ? "Greater" : "Lesser" << endl;
Functions are the first kind of abstraction to break up large pieces of code into logical sections. In C++, functions need to have function prototypes or function declarations that need to be
seen by the compiler before the function definintion is seen. The prototype is typically located in the header file although it can be in the cpp file.
One can return a value to the caller from a function. If there is no value being returned specify void
.
Example:
int multiplyNumbers (int a , int b)
{
return a * b;
}
The function is invoked or called as follows:
int product = multiplyNumbers(5,3);
Starting from C++14, one can let the compiler infer the return type of a function automatically. Example:
auto divideNumbers(int number1, int number2)
{
if(number2 != 0)
{
return number1 / number2;
}
else
{
return 0;
}
}
Current name of the function is available via the local predefined __func__
variable. This can be useful for logging.
Arrays hold a sequence of values, all of the same type, each of which can be accessed by an integer index. The indices start at 0 and end at length of the array minus 1.
The specified size must be a literal constant, constant, or constant expression (constexpr
). Example:
int odds[3];
odds[0] = 1;
odds[1] = 3;
odds[2] = 5;
Zero initialization can be accomplished as follows:
int odds[3] = {0};
Initializer lists can be specified as follows:
int odds[] = {1,3,5,7};
C++17 std::size()
function can be used (need to #include<array>
). For older compilers, the sizeof
operator can be used:
int arraySize = sizeof(odds)/ sizeof(int);
C++ allows multidimensional arrays as well. Usually arrays don't go beyond 2 or 3 dimensions.
PieceType chessBoard[8][8];
chessBoard[0][0] = PieceType::Rook;
Recommendation is to avoid C-style arrays in favor of the standard library std::array
or std::vector
.
Vector is an array that can dynamically grow or shrink. The vector takes a template parameter which is the data type of the values stored inside the vector:
Example:
using std::vector
vector<int> odds;
odds.push_back(1);
odds.push_back(3);
odds.push_back(5);
There are four types of loops: while
loop, for
loop, do/while
loop, and range-based for
loop.
Example of while loop:
int i = 0;
int ary[10] = {0};
while(i < 10)
{
ary[i] = i * 2;
}
Example of range based for loop is below. The range based for loop iterates over a copy of every element in the collection. To avoid making copies, use a reference variable as discussed later.
std::array<int, 4>ary = {1,2,3,4};
for (int k : ary)
{
std::cout << k << endl;
}
These are defined in the <initializer_list>
header file and enable the user to write functions to accept a variable number of arguments. Example:
#include <initializer_list>
using namespace std;
int multiplyMany(initializer_list<float> nums)
{
float product = 1;
for (float val : nums)
{
product *= val;
}
return total;
}
Function can be invoked as:
float prod = multiplyMany({3,4,5});
float prod2 = multiplyMany({10,20,30,40})
The string
type lives in the std
namespace. string
s can be used similar to character arrays:
string theString = "To be or not to be";
cout << "The first character is "<<theString[0] << endl;
Gregoire, M. (2018). Professional C++. Indiana, IN: John Wiley & Sons.
Comments
Post a Comment