Cpp datatypes

From wikinotes

Variable Basics

variable typing

char firstname, middlename, lastname;           // group variable definitions
decltype(firstname) username;                   // define variable `username` using same type as `firstname`
auto username = firstname;                      // copy variable type
std::cout << typeof(var).name() << std::endl;   // print object type (!works inconsistently!)

pointers (reference/dereference)

myfunc(&age);                          // pass pointer to `age`
myfunc(*age);                          // pass value of pointer `age`
int *age;                              // define pointer to an int (`age`s value is pointer to value of int age).

For more details, see Cpp pointers & references.

typedef

// typedef allows you to alias a keyword as a type, with the goal
// of communicating intent.
// 
typedef int life_remaining;
typedef int life_max;

// all below functions return an int,
// but we communicate the intent using different typedefs.
life_max       set_total_life(int);
life_remaining add_hearts(int);
life_remaining rm_hearts(int);

Basic DataTypes

// Text
char mychar = 1;      //Stores one byte as an integer.
char mychar = abcd;  //Also stores text, but as an array this is myVariable2[4] (4 characters)

string mystring = "abcd";         //String
string mystring	= string(mychar); //Convert Char to string
// Numbers
int     myVariable = 1;     //Integer
float   myVariable = 1.05;  //Single precision floating point value (4bit precision)
double  myVariable = 1.05;  //Double precision floating point value (8bit precision)
wchar_t myVariable = abcd;  //wide character type(don't understand)
// Misc
void                  //no type (used for functions without return values)
bool myVariable	= 1;  //Stores 1 or 0
bool myVariable = true;
bool myVariable = false;
int* p = nullptr;
// Conversion
myint = atoi(myChar);                    //Convert Char to Int
myint = atoi(myString.c_str());          //Convert string to Int
static_cast<int>(floatrA * floatB)       //converts result to integer
string myString	= string(myChar);        //Convert Char to string

Numbers

int  num, other_num, yet_another_num;

int num = -25;
long num = -3.14;

// positive-only
unsigned int num = 25;
unsigned long num = 3.14;
// Abbreviations
num = 25u;      // unsigned
num = 3.14l;    // long
num = 3.14159L; // Double Long
num = 3.14159F; // Float
// number types
int num = 25;    // decimal number (base 10)
int num = 031;   // octal          (base  8)
int num = 0x019; // hexidecimal    (base 16)

Signed vs Unsigned

integers in C/C++ can be signed or unsigned.

  • the range of a signed integer is split in half. one half negative, one half positive. (ex: -30 to 30)
  • the range of an unsigned integer is from 0 to the full range. (ex: 0 to 60)


Strings

#include <string>        // the string datatype requires the string library
string town = "ottawa";  // strings must use double quotes
cout << town << endl;    // endl indicates a newline

string long_name = "this is a very long string and \
                    it continues onto a second line \
                    and a third."

string raw_str = R("this is a raw string \!/()'~ul")

Arrays

An array in C++ is a fixed-size list of items all sharing the same type. Arrays in C++ are not scaleable.

you cannot return arrays from functions (use vectors instead)

// define array (size must be explicitly defined)
int billy[5] = { 16, 2, 77, 40, 12071 }; 

//You can use a variable for the size, but it must be a constant
const int num_items = 5;
double distance[num_items] = {44.14, 720.52, 96.08, 468.78, 6.28};

//Number of items in string array  (array-size-bytes / array-vartype-bytes)
sizeof(myarray) / sizeof(string);

Vectors

Unlike Arrays, Vectors in C++ are scalable - they can be expanded and contracted as needed.

Vector Declaration

vector<bool> testVector;                // Boolean Vectors are made specially for space efficiency. Each value is only 1 bit instead of 8

vector<int>   int_vector;
vector<int>   int_vector(10);           // Int vector with storage space for 10 values (defaults to dynamically resizing)
vector<int *> int_ptr_vector;           // vector stores pointers

vector<float> testVector(5,1.0);        // Float Vector with storage space for 5, Each value initialized at 1.0

Vector Utilities

size(testVector);				//number of elements in a vector

capacity(testVector);		//the number of elements that can be added to avector
									//before the program needs to allocate more memory to 
									//it (for automatically managed vectors)
									//ex: say a vector is declared and uses 16 bits of memory
									//    which is equivalent to two characters. If a third character
									//    was added, it might bump the memory allocation to 32bits
									//    which would allow 4 characters (even though you are only using 3)
									//    the capacity then would be 1.


max_size(testVector);		//the maximum number of items that can be stored in a vector, ignoring the
									//current memory allocation, but depending on the computer architecture, ram etc.

Structs

#include <iostream>

struct product {
  int weight;
  double price;
};

int main(int argc, char *argv[])
{
    product apple;
    apple.weight = 0;
    apple.price = 1.1;
    std::cout << apple.price;
    return(0);
}

Enums

typedef enum Days {
    day_monday =  0,
    day_tuesday = 1
} Days;


int main(int argc, char *argv[])
{
    Days day = day_monday;
    std::cout << day << std::endl;
    if (day == day_monday)
    {
        std::cout << "Its Monday";
    }
    return(0);
}

Converting Between Types

Assigning a variable, with it's type in parentheses before the value converts that variable into the type between parentheses.

int   int_num;
float float_num;

int_num = 6;
float_num = (float) int_num;		// converts 6 to a float.
string mystr = "my string value";
int    myint;

stringstream(mystr) >> myint;		// convert from mystr to myint