Lesson 5 +30 XP

Data Types, Type Compatibility & Variables

Data Types, Type Compatibility & Variables

A data type tells the compiler how much memory a value needs and what operations are allowed on it. C++ keeps all of C's types, adds bool, wchar_t and class, and is stricter than C about mixing types. This lesson also covers how C++ declares and initialises variables, including reference variables.

1. Classification of Data Types

C++ data types: built-in, user-defined and derivedC++ data types: built-in, user-defined and derived

CategoryTypes
Built-in (basic)integral: int, char, bool, wchar_t; floating: float, double; void
User-definedstruct, union, class, enum
Derivedarrays, functions, pointers, references

Built-in types

Sizes depend on the compiler and machine. These are the usual values on a 32-bit or 64-bit system:

TypeTypical sizeTypical range
char1 byte−128 to 127
unsigned char1 byte0 to 255
short int2 bytes−32,768 to 32,767
int4 bytesabout −2.1 × 10⁹ to 2.1 × 10⁹
unsigned int4 bytes0 to about 4.29 × 10⁹
long int4 or 8 bytesat least the range of int
float4 bytesabout 3.4 × 10⁻³⁸ to 3.4 × 10³⁸, 6-7 digits
double8 bytesabout 1.7 × 10⁻³⁰⁸ to 1.7 × 10³⁰⁸, 15 digits
long double10, 12 or 16 bytesmore precision than double
bool1 bytetrue or false
wchar_t2 or 4 byteswide characters (Unicode)

Modifiers signed, unsigned, short and long change the range of int and char (and long also applies to double).

void has two uses: to say a function returns nothing (void show()), and to declare a generic pointer void* that can hold the address of any type.

User-defined types

  • struct groups related data. In C++ a structure can also hold functions and access specifiers; the only difference from class is that its members are public by default.
  • union is like a structure, but all members share the same memory, so only one holds a value at a time. Its size is that of its largest member.
  • class groups data and functions; members are private by default.
  • enum creates a set of named integer constants. In C++ the enum name is a type name: enum shape { circle, square }; shape s; (no enum keyword needed in the declaration). An int cannot be assigned to an enum variable without a cast.

Derived types

  • Arrays: a sequence of elements of one type. In C++, the array size must leave room for the '\0' of a string literal: char s[3] = "xyz"; is an error in C++ (allowed in C).
  • Functions: C++ adds prototypes (required), overloading, default arguments, inline functions.
  • Pointers: as in C, plus constant pointers and pointers to constants.
  • References: another name for an existing variable (section 4).
DeclarationMeaning
int* ppointer to int
const int* ppointer to a constant: *p cannot be changed, p can
int* const p = &xconstant pointer: p cannot be changed, *p can
const int* const p = &xneither can be changed
C++
#include <iostream>
using namespace std;

struct Point { // struct with a function: members public by default
    int x, y;
    void show() {
        cout << "(" << x << ", " << y << ")" << endl;
    }
};

union Value { // all members share one block of memory
    int i;
    float f;
    char c;
};

enum Shape {
    CIRCLE,
    SQUARE,
    TRIANGLE
};

int main() {
    Point p = {3, 4};
    p.show();

    Value v;
    v.i = 65;
    cout << "union size = " << sizeof(v) << ", as char = " << v.c << endl;

    Shape s = SQUARE; // no 'enum' keyword needed in C++
    cout << "SQUARE = " << s << endl;

    int a = 10, b = 20;
    const int* pc = &a; // pointer to constant
    pc = &b;            // OK: the pointer itself may change
    // *pc = 5;                // error: the value is read-only through pc
    int* const cp = &a; // constant pointer
    *cp = 15;           // OK: the value may change
    // cp = &b;                // error: the pointer is read-only
    cout << "*pc = " << *pc << ", a = " << a << endl;
    return 0;
}

Output:

OUTPUT
(3, 4)
union size = 4, as char = A
SQUARE = 1
*pc = 20, a = 15

2. Type Compatibility

C++ is much stricter than C about type compatibility, in order to catch mistakes and to make function overloading possible.

Rule in C++C behaviour
short int, int and long int are distinct typestreated as more or less interchangeable
char, signed char and unsigned char are three different typessimilar
a character constant 'A' has type char, so sizeof('A') is 1type int, so sizeof('A') is usually 4
a void* cannot be assigned to another pointer type without a castallowed implicitly
an int cannot be assigned to an enum variable without a castallowed
char s[3] = "xyz"; is an error (no room for '\0')allowed (no terminator stored)
every function must be declared before use (prototype)old C allowed implicit declarations
C++
#include <iostream>
using namespace std;

enum Color {
    RED,
    GREEN,
    BLUE
};

int main() {
    cout << "sizeof('A') = " << sizeof('A') << endl; // 1 in C++

    int n = 42;
    void* gp = &n;      // any pointer converts TO void*
    int* ip = (int*)gp; // but FROM void* needs an explicit cast
    cout << "*ip = " << *ip << endl;

    Color c = (Color)2; // int to enum needs a cast
    cout << "c = " << c << endl;
    return 0;
}

Output:

OUTPUT
sizeof('A') = 1
*ip = 42
c = 2

3. Variables: Declaration and Dynamic Initialisation

A variable is a named memory location whose value can change.

Declaration anywhere. C requires all variables at the start of a block. C++ allows a variable to be declared anywhere in the scope, right before its first use. This makes programs easier to read because a variable is declared where it is needed.

Dynamic initialisation. C++ allows a variable to be initialised at run time with an expression whose value is known only then, not just with a constant.

C++
#include <iostream>
using namespace std;

int main() {
    int n = 5;
    int sum = 0;
    for (int i = 1; i <= n; i++) { // i declared at its point of use
        sum = sum + i;
    }
    float average = (float)sum / n; // dynamic initialisation: computed at run time
    cout << "sum = " << sum << ", average = " << average << endl;
    return 0;
}

Output:

OUTPUT
sum = 15, average = 3

4. Reference Variables

A reference variable is an alternative name (alias) for an existing variable. Both names refer to the same memory location, so a change through either name is seen through both.

data-type \& reference-name = variable-name;

Rules:

  1. A reference must be initialised when it is declared.
  2. Once bound, it cannot be made to refer to another variable.
  3. There are no null references, and no arrays of references.
  4. The & here is not the address-of operator; it means "reference to".
C++
#include <iostream>
using namespace std;

int main() {
    float total = 100;
    float& sum = total; // sum is another name for total

    cout << "total = " << total << ", sum = " << sum << endl;
    sum = sum + 50; // changes total as well
    cout << "total = " << total << ", sum = " << sum << endl;
    cout << "same address? " << (&total == &sum) << endl;

    int x = 10;
    int& r = x;
    int y = 99;
    r = y; // copies 99 into x; r still refers to x
    cout << "x = " << x << ", y = " << y << endl;
    return 0;
}

Output:

OUTPUT
total = 100, sum = 100
total = 150, sum = 150
same address? 1
x = 99, y = 99

The main use of references is in passing arguments to functions (call by reference) and returning by reference, covered in Lesson 9.

PointerReference
holds an address; needs * to reach the valueis another name; used like the variable itself
may be left uninitialisedmust be initialised
can be changed to point elsewherealways refers to the same variable
can be NULLcannot be null
has its own memoryusually needs no extra memory of its own
💡 Tip

Key points to remember

  • Types: built-in (int, char, bool, float, double, void, wchar_t), user-defined (struct, union, class, enum), derived (array, function, pointer, reference).
  • struct members are public by default; class members are private by default.
  • C++ is stricter than C: sizeof('A') = 1, void* needs a cast, char s[3] = "xyz" is an error.
  • Variables can be declared anywhere and initialised dynamically.
  • A reference is an alias: must be initialised, cannot be reseated, cannot be null.
🎯 END-TERM EXAM PREP

📝 IPU End-Term Exam Corner (5-10 Marks)

  • Q1. Explain the data types available in C++ with a diagram. (5 Marks)
  • Write: the classification diagram, the built-in table with sizes, and one line each on struct, union, class, enum.
  • Q2. What is type compatibility? How is C++ stricter than C? (5 Marks)
  • Write: the seven-row table and the sizeof('A') / void* program.
  • Q3. What is a reference variable? How is it different from a pointer? (5 Marks)
  • Write: the syntax, the four rules, the total/sum program and the pointer vs reference table.
  • Q4. What is dynamic initialisation of variables? Give an example. (2.5 Marks)
  • Q5. Differentiate between a structure and a union. (2.5 Marks)