C++ L03 – Variables, types and operators

In order to be able to do something interesting and useful with C++, we have to take advantage of computer memory. The way we use computer memory is though variables.

On this post, I will show how you can define and use variables and apply operations on them.

One of the most important features of C and C++ is that everything has a type that is known at compile time. In fact, this is one of the reasons that C and C++ are generally faster than dynamic-type languages like Python or Javascript. Failing to use the appropriate type will result in a compile error.

In C++, before we use anything with a name we have to at least declare it somewhere before. This holds true for variables. The following code demonstrates variables and operators.

#include <iostream>

//this line is a comment, everything between // and the end of the line is ignored by the compiler
//this style of comments were introduced in C++
/*
    C supports only this type of comments
    variable definition is of the form:
    type name;

    valid names cannot start with a number
    names as everything else in C++ is case sensitive, so
    variable is different than VAriable
*/
int g1;//global variable

int main()
{
    int x;// integer, size depends on architecture
    int y,z;// multiple variables of the same type, declared on the same spot using the ',' operator
    int k = 5;// definition and initialization
    int l=2,m;// mix and match
    std::cout << "m is not initialized: " << m << "\n";
    //non initialized variables usually have garbage values (what happened to be leftover in memory)
    //'\n' is a control character that means change line (line feed)
    //there are other control characters such as '\t' for tab and '\r' for carriage return   
    std::cout << g1 << "\n";// remember the global variable at the top of the program? globals are auto initialized with zero
    //declared variables are available to all {} blocks at deeper level
    //main is a level down than global scope

    char c;// single character, essentially a byte
    char c1 = '0';// the value of '0' is not equal to 0 but is equal to the value of '0' in ASCII encoding
    // characters between single quotes ' are of type char. You can only put a single character between '
    // exceptions are escape sequences (\n \t etc) that count as a single character

    float f;// floating point number
    float f1 = 0.234;// floating point variable initialized with floating point literal
    double d;// double precision floating point number

    bool bo;//boolean , true of false
    bo = false;

    m = k + l;//assignment and addition is pretty straight forward
    std::cout << m << "\n";
    std::cout << k + l << "\n";// operations usually return a type, you can pass that to other operators and/or functions
    std::cout << k - l << " " << k*l << "\n";//subtraction and multiplication
    std::cout << (k-l)*m << "\n";// operators have priorities, */ have priority over +-; operations inside () are calculated first

    std::cout << (l = 1);// assignment returns the assigned value
    l = m = 1;// equivelant to l = (m = 1)
    l = l + 1;// increment l by 1
    l += 5;// increment l by 5
    l -= m;// decrement l by m
    l *= 5;// multiply assign
    l /= 5;// divide assign
    std::cout << l << "\n";
    std::cout << l++ << "\n";// increment l by one and return the value before the incrementation
    std::cout << ++l << "\n";// increment l by one and return the value after the incrementation
    std::cout << l--  << "\n";// also available for decrement
    std::cout << --l  << "\n";

    std::cout << 10/3 << "\n";// the result here is 3; when dividing int with int , the result is an int. Result is truncated
    std::cout << 10/3.0 << "\n";// the result here is 3.33; when dividing float with int or int with float, the result is a float
    //what about variables? the solution is to convert (type cast) one of them to floating point (float or double)
    std::cout << 10/(float)l << std::endl;
    float ff = 5;// values are autocasted. 5 is an int that is converted to float to be assigned to ff

    std::cout << 'a' + 1 << std::endl;// remember what we said about character literals

    bool a = true,b = false;
    l = a?10:-10;// ternary operator. if the condition before ? is true then returns value before :, else the second value

    std::cout << (a && b?"true":"false") << std::endl;// and operator, returns true only if both operands are true
    std::cout << (a || b?"true":"false") << std::endl;// or operator, returns true if at least one of the operands are true
    std::cout << (a && 5?"true":"false") << std::endl;// numbers can be converted to boolean values as well, 0 is false, anything else is true
    std::cout << (a && 0?"true":"false") << std::endl;// numbers can be converted to boolean values as well, 0 is false, anything else is true

    std::cout << (l >  5?"true":"false") << std::endl;// comparison operators return booleans
    std::cout << (l >= 5?"true":"false") << " " << (l <= 5?"true":"false") << std::endl;// greater than or equal, less than or equal
    std::cout << (l == 5?"true":"false") << " " << (l != 5?"true":"false") << std::endl;// equal, not equal
    //notice that equality is checked with == and not single =
    //single = is asignment, and as we saw it returns a value that can potentialy be autocasted to boolean
    //that means that asignment is mostly valid for boolean checks
    //so, a very common mistake for new players is using = instead of == for equality checks


    return 0;
}

Bonus homework

If you compile the previous code, you are going to get warnings. Try to understand what those warnings mean and how to resolve them

Author: Lefteris Chatzipetrou

Lefteris is a Co-Founder and CTO over at HAM Systems. He has wide experience in electrical engineering including electronics and embedded systems, mobile, web services and video games development.

Leave a Reply

Your email address will not be published. Required fields are marked *