2.1) C Data types, variables, and constants
In C programming, understanding data types, variables, and constants is fundamental as they form the building blocks for creating and manipulating data.
Let’s dive into each of these concepts in detail, along with examples for various data types.
Table of Contents
C Data Types:
A data type is a classification that specifies which type of value a variable can hold. C provides several basic data types that can be broadly categorized into three groups: integral data types, floating-point data types, and character data types.
Integral Data Types:
int
: Represents whole numbers (positive, negative, or zero).char
: Represents a single character.short
: Represents short integers.long
: Represents long integers.long long
: Represents very long integers (C99 standard).
Floating-Point Data Types:
float
: Represents single-precision floating-point numbers.double
: Represents double-precision floating-point numbers.long double
: Represents extended-precision floating-point numbers (may vary by platform).
Character Data Types:
char
: Represents individual characters using ASCII values.
Variables:
A variable is a named storage location in memory that holds a value of a specific data type. Variables must be declared before they can be used, specifying their data type. Here’s how you declare variables:
data_type variable_name;
Examples of variable declarations:
int age;
char grade;
float temperature;
Constants:
A constant is a value that cannot be changed during the execution of a program. C supports both numeric constants (integer and floating-point) and character constants (single characters enclosed in single quotes). Constants can be used directly in expressions.
Examples of constants:
const int MAX_VALUE = 100;
const float PI = 3.14159;
const char NEWLINE = '\n';
Examples for Each Data Type:
Integral Data Types:
int score = 95;
char letterGrade = 'A';
short population = 32000;
long worldPopulation = 7800000000L;
long long bigNumber = 123456789012345LL;
Floating-Point Data Types:
float price = 49.99f;
double pi = 3.141592653589793;
long double veryPrecise = 0.12345678901234567890L;
Character Data Types:
char firstInitial = 'J';
char newline = '\n';
Remember that each data type has a specific range of values it can hold, which affects the memory allocated for the variable and the precision of the data. Choosing the appropriate data type based on the requirements of your program is essential for efficient memory usage and accurate calculations.