If you’re a noob with some programming experience like me, it’ll be best if you start with a blog post I wrote June 5th 2019: Hello World program in C++

That article will step through installing C++ on your machine, and making sure you can compile a .cpp file into binary. This file is the executable file to run your program from.

Variables and Types

Since C++ is a strongly typed programming language, we have to define the type of a variable at its declaration.

int num;

num = 5;

When double quotation marks " " are placed around a variable it makes it a string constant, or string literal. We’ll see an error if we place quotation marks around our previous example.

num = "5";

output:

playground.cpp:7:11: error: assigning to 'int' from incompatible type
      'const char [2]'
    num = "5";
          ^~~
1 error generated.

Once I run the command to compile my program, this error will be spit out. On the first line it has the name of my file and the number of the line the error occured on. It’s descriptive in that it is telling me that I cannot assign a char type to an int variable. The last line indicates that 1 error was generated from my program.

Variables and Constants

Legally, we can write variables in camelCase: myListOfThings or with a starting underscore: _myListOfThings or with a capital letter: MyListOfThings

We may not use numbers to begin variable names or include special characters anywhere in variable names.

Constants

Constants can be declared at the top of our files, using the keyword const and like other languages, these values are not meant to be changed - and cannot be - in our program.

Examples:

const double INTREST_RATE = 0.2459;

const double PI = 3.14;

More Types & Type Conversion

We can’t convert types without being aware of them first, so let’s briefly review:

Boolean Type
  • Set to either true or false

Example:

int main()
{
    bool isOn;
    isOn = true;
    cout << isOn;
    return 0;
}

Output will be 1, as the bool outputs 0 for false and 1 for true values.

String Type
  • Things in quotes!

If you look up an ASCII chart, you’ll see each string char type has an associated number. On most systems, the char type is 1 byte because each character is represented by a small integer.

#include<iostream>
using namespace std;

int main()
{
    char letter;

    letter = 65;
    cout << letter << endl;

    letter = 66;
    cout << letter << endl;
    return 0;
}    

The output of this program would be A and B respectively.

Character constants vs string constants

If you need to store a single letter in a variable, you can use single quotation marks to signify a character constant

char grade = 'A'

If you use double quotes, it’s an example of a string constant

char name = "Emily"

You can store A as a string constant by using double quotes; the only difference is that it’ll take up 2 bytes of memory versus the 1 byte of memory the character constant fills.

Number Type
  • Numbers!

    • Integers
Type Bytes Size
short 2 bytes -32,768 to 32,767
unsigned short 2 bytes 0 to 65,535
int 4 bytes -2,147,483,648 to 2,147,483,647
unsigned int 4 bytes 0 to 4,294,967,29
long 4 bytes -2,147,483,648 to 2,147,483,647
unsigned long 8 bytes 0 to 4,294,967,295

Bringing them together in an example:

#include<iostream>
using namespace std;

int main()
{
    int checking;
    unsigned int miles;
    long days;

    checking = -20;
    miles = 4276;
    days = 190000;

    cout << "The journey has been  " << miles << "miles.";
    cout << "\nOur bank account balance is " << checking;
    cout << "\nI feel " << days << " old.";
    return 0;
}
  • Floating point
Type Bytes Size
float 4 bytes +/- 3.4E-38 to +/-3.4E38 (7 sig fig)
double 8 bytes +/- 1.7E-308 to +/-1.7E308 (16 sig fig)
long double 12 bytes +/- 1.7E-308 to +/- 1.7E308 (16 sig fig)

Here’s a C++ program to print out the size of all datatypes:

// C++ program to sizes of data types
#include<iostream>
using namespace std;

int main()
{
    cout << "Size of char : " << sizeof(char)  
      << " byte" << endl;
    cout << "Size of int : " << sizeof(int)
      << " bytes" << endl;
    cout << "Size of short int : " << sizeof(short int)  
      << " bytes" << endl;
    cout << "Size of long int : " << sizeof(long int)  
       << " bytes" << endl;
    cout << "Size of signed long int : " << sizeof(signed long int)
       << " bytes" << endl;
    cout << "Size of unsigned long int : " << sizeof(unsigned long int)  
       << " bytes" << endl;
    cout << "Size of float : " << sizeof(float)  
       << " bytes" <<endl;
    cout << "Size of double : " << sizeof(double)  
       << " bytes" << endl;
    cout << "Size of wchar_t : " << sizeof(wchar_t)  
       << " bytes" <<endl;

    return 0;
}

And bringing them together in an example:

#include<iostream>
using namespace std;

int main()
{
    float distance = 1.496E8; //km
    double mass = 1.989E30; //kg

    cout << "The sun is  " << distance << " kilometers away.\n";
    cout << "The sun\'s mass is  " << mass << " kilograms.\n";
    return 0;
}

NOTE on finding the size of a data type:

int myNumber = 555;

cout << "The size of this variable is " << sizeof(myNumber);

Output: The size of this variable is 4

(Because the size of an int type is 4 bytes!)

Casting

There are different ways of describing the act of changing one type to another type in a program. I’ve seen it referenced as conversion, coercion and casting and I’ll explain the subtle differences below.

⭐️ This is different than TRUNCATING which happens when an int is assigned a decimal such as:

int number;
number = 5.5;

Output will be 5 due to the program truncating the decimal. Since we defined it as an int, it’ll still take up 4 bytes of memory in our program.

Type coercion

When an operator’s operands are of different data types, C++ will automtically convert them to the same data type. This may affect the results of mathematical expressions.

This implicit/automatic conversion is known as type coercion and values can be promoted or demoted to convert to data types that hold larger or smaller byte amounts.

Keep in mind when doing arithmetic operations, char, short and unsigned short values are automatically promoted to int type. IF an unsigned short holes a value larger than can be held by an int, it is promoted to unsigned int.

Type casting

Type casting occurs when we EXPLICITLY wish to promote or demote a value.

double number = 3.7;
int val;
val = static_cast<int>(number);

Output: A copy of the value in number is returned, converted to int. So, the number 3 is now stored in val.

Let’s create a program with input and output, incuding our first expression:

#include<iostream>
using namespace std;

int main()
{
    int books,
        months;
    double booksPerMonth;

    cout << "How many books will you read? ";
    cin >> books;
    cout << "How many months will it take? ";
    cin >> months;

    booksPerMonth = static_cast<double>(books) / months;
    cout << "That is " << booksPerMonth << " books per month.\n";
    return 0;
}

INPUT 1: 30 (books)

INPUT 2: 7 (months)

Note: Had we done the division inside the parentheses (books/months) it would have resulted in 4 as the answer. Since we wanted it converted to a double type in order to get the exact amount, the output is 4.28571

You can also cast an ASCII code number to its corresponding char:

int main()
{
    int number = 65;
    cout << static_cast<char>(number) << endl;
    return 0;
}

Output: A

Arithmetic operators and expressions

() - + * / %

Example expression:

a = (3 * x + 2) / (4 * y - 1)

  • Evaluate parentheses first

  • Then evaluate multiplication and division

  • Then evaluate addition and subtraction

We can also use combined assignment operators in operations:

x += b +5; is x = x + (b + 5);

Which can be done with -+ *= /= %= as well.

Also available to us is a math library to use functionality such as finding the absolute value of a number, cosign, exponential function, rounding, square root and more!

In order to utilize this library, put #include<cmath> at the top of your program. I’ll give more examples using the math library in my next blog post - which will also include manipulating files, loops, decision structures and functions.

Happy coding!

E


Got Questions❓, Comments 🗣 or Edits ✍

Use the Twitter thread below and hashtag #E4Everything to get in touch with me regarding this blog post:

Previous: CookiesNext: C++ Continued