How to Use Data Types in C++
C++ offers seven fundamental data types, which can symbolize any type of information and are built into the compiler. Five of these types are derived from C: void, int, float, double and char. C++ defines the other two: bool and wchar_t. Data types are essential to master because a program without data types has no value. Read on to learn how to use data types in C++.
Instructions
-
-
1
Learn the significance of each data type. A void type means "no data" or represents a generic pointer. The int type stores positive or negative whole numbers and is 16 or 32 bits long. "Float" (32 bits) represents decimal numbers with a moveable (floating) decimal point, and double is an extra precise float that's 64 bits long. "Char" (8 bits) represents printable characters, and wchar_t can store a wide character literal. "Bool" (8 bits) denotes true or false.
-
2
Use the following syntax to declare a data type in your program as the following example shows: data type keyword, space, variable name, comma, space, other variable names, semicolon. Precede the data type keyword by a data type modifer, if necessary. See Step 3 for explanations on type modifiers.
int num1, num2, num3; -
-
3
Learn the type modifiers: signed, unsigned, short and long. If you put one by itself, the compiler assumes you mean int. The short modifier makes an int 2 bytes while long makes it 4 bytes.
-
4
Initialize a variable by putting an equals sign after it and giving it a value. You can do this during the declaration or after it.
int x = 14, y; // during declaration
y = 34; // after declaration -
5
Form an arithmetic expression using data types as follows:
unsigned int seconds = 60, minutes = 60, hours = 24, total;
total = hours * minutes * seconds; -
6
Create a more complex data type by using char. An array is a data structure that can hold a row of elements of the same data type. An array of char functions as a string.
char word[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
-
1
Tips & Warnings
Use data qualifiers such as const, static, volatile, register or the star operator to give the compiler additional information about how to store the data.
Pointers are special data types that store a memory address and have the same type as the variable they point to in memory.
C++ lets programmers define custom-made data types; these are called classes.