Loading lessons...
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 derived
| Category | Types |
|---|---|
| Built-in (basic) | integral: int, char, bool, wchar_t; floating: float, double; void |
| User-defined | struct, union, class, enum |
| Derived | arrays, 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:
| Type | Typical size | Typical range |
|---|---|---|
char | 1 byte | −128 to 127 |
unsigned char | 1 byte | 0 to 255 |
short int | 2 bytes | −32,768 to 32,767 |
int | 4 bytes | about −2.1 × 10⁹ to 2.1 × 10⁹ |
unsigned int | 4 bytes | 0 to about 4.29 × 10⁹ |
long int | 4 or 8 bytes | at least the range of int |
float | 4 bytes | about 3.4 × 10⁻³⁸ to 3.4 × 10³⁸, 6-7 digits |
double | 8 bytes | about 1.7 × 10⁻³⁰⁸ to 1.7 × 10³⁰⁸, 15 digits |
long double | 10, 12 or 16 bytes | more precision than double |
bool | 1 byte | true or false |
wchar_t | 2 or 4 bytes | wide 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
structgroups related data. In C++ a structure can also hold functions and access specifiers; the only difference fromclassis that its members are public by default.unionis 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.classgroups data and functions; members are private by default.enumcreates a set of named integer constants. In C++ the enum name is a type name:enum shape { circle, square }; shape s;(noenumkeyword needed in the declaration). Anintcannot 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).
| Declaration | Meaning |
|---|---|
int* p | pointer to int |
const int* p | pointer to a constant: *p cannot be changed, p can |
int* const p = &x | constant pointer: p cannot be changed, *p can |
const int* const p = &x | neither can be changed |
#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:
(3, 4)
union size = 4, as char = A
SQUARE = 1
*pc = 20, a = 152. 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 types | treated as more or less interchangeable |
char, signed char and unsigned char are three different types | similar |
a character constant 'A' has type char, so sizeof('A') is 1 | type int, so sizeof('A') is usually 4 |
a void* cannot be assigned to another pointer type without a cast | allowed implicitly |
an int cannot be assigned to an enum variable without a cast | allowed |
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 |
#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:
sizeof('A') = 1
*ip = 42
c = 23. 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.
#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:
sum = 15, average = 34. 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.
Rules:
- A reference must be initialised when it is declared.
- Once bound, it cannot be made to refer to another variable.
- There are no null references, and no arrays of references.
- The
&here is not the address-of operator; it means "reference to".
#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:
total = 100, sum = 100
total = 150, sum = 150
same address? 1
x = 99, y = 99The main use of references is in passing arguments to functions (call by reference) and returning by reference, covered in Lesson 9.
| Pointer | Reference |
|---|---|
holds an address; needs * to reach the value | is another name; used like the variable itself |
| may be left uninitialised | must be initialised |
| can be changed to point elsewhere | always refers to the same variable |
can be NULL | cannot be null |
| has its own memory | usually needs no extra memory of its own |
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). structmembers are public by default;classmembers 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.
📝 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/sumprogram 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)