Extra 5% OFF Use Code: OL05
Free Shipping over ₹999

Data Types & Variables

What is Data type ?

In C programming, a data type specifies the type of data that can be stored in a variable. It determines the range of values that the variable can hold and the operations that can be performed on the variable.

For example, the integer data type can hold whole numbers (positive, negative, or zero) and can perform arithmetic operations like addition, subtraction, multiplication, and division. The character data type can hold a single character, such as a letter or symbol, and can perform operations like comparison. However, it can also be used to hold integer values between -128 to 127 (or 0 to 255 if unsigned).

In C programming, there are several built-in data types, including:

Basic or Primitive Data Types

Here’s a detailed look at the main primitive data types in C, along with examples of their usage.

Data TypeDescriptionExample CodeSizeRange
intUsed to store integers (whole numbers), both positive and negative.int age = 30;Typically 4 bytes-2,147,483,648 to 2,147,483,647
unsigned intUsed to store only non-negative integers.unsigned int score = 90;Typically 4 bytes0 to 4,294,967,295
floatUsed to store single-precision floating-point numbers (decimals).float height = 5.9;4 bytes±3.4E-38 to ±3.4E+38
doubleUsed to store double-precision floating-point numbers, with more precision than float.double distance = 384400.0;8 bytes±1.7E-308 to ±1.7E+308
charUsed to store single characters (letters, symbols) or small integers within -128 to 127 (signed char). Each char typically uses 1 byte of memory.char grade = 'A';1 byte-128 to 127 (signed)
unsigned charUsed to store only non-negative character values or small positive integers.unsigned char level = 200;1 byte0 to 255
shortUsed to store short integers, with a smaller range than int.short age = 18;2 bytes-32,768 to 32,767
longUsed to store large integers, with a larger range than int.long distance = 100000L;Typically 4 or 8 bytes-2,147,483,648 to 2,147,483,647 (4 bytes) or larger
unsigned longUsed to store large non-negative integers.unsigned long count = 500000UL;Typically 4 or 8 bytes0 to 4,294,967,295 (4 bytes) or larger
long doubleUsed to store extended-precision floating-point numbers.long double area = 150.45L;10, 12, or 16 bytes (depends on system)Larger range than double

Examples of Primitive Data Types

Let’s look at these data types in a C program, demonstrating their usage:

#include <stdio.h>

int main() {
    int age = 25;                   // integer type variable
    float height = 5.8;              // single-precision floating-point variable
    double distance = 384400.0;      // double-precision floating-point variable
    char grade = 'A';                 // character type variable
    signed char signedChar = -100;     // Signed char
    unsigned char unsignedChar = 200;  // Unsigned char
    short score = 123;         // short integer
    long population = 8000000000L; // long integer
    long double area = 120.56789L; // long double precision floating-point

    printf("Age: %d\n", age);
    printf("Height: %.2f\n", height);
    printf("Distance to Moon: %.1lf km\n", distance);
    printf("Grade: %c\n", grade);
    printf("Signed Char: %d\n", signedChar);
    printf("Unsigned Char: %u\n", unsignedChar);
    printf("Score: %d\n", score);
    printf("Population: %ld\n", population);
    printf("Area of land: %.5Lf\n", area);

    return 0;
}


Output:

Age: 25
Height: 5.80
Distance to Moon: 384400.0 km
Grade: A
signedChar: -100
unsignedChar: 200
Score: 123
Population: 8000000000
Area of land: 120.56789

Explanation

  • int (int age = 25;): Holds integer values like age, temperature, or counts.
  • float (float height = 5.8;): Suitable for decimal values requiring single precision, such as heights or distances with small decimal parts.
  • double (double distance = 384400.0;): Useful for more precise decimal values, often used in scientific calculations.
  • char (char grade = 'A';): Stores single characters, such as letter grades or symbols.
  • short (short score = 123;): Typically used when a smaller integer range is needed, saving memory for values like test scores or levels.
  • long (long population = 8000000000L;): Suitable for large integer values like population or financial data.
  • long double (long double area = 120.56789L;): Used when higher precision for decimal values is required, typically in scientific applications.

Derived Data Types

Derived data types are more complex than primitive types and are constructed using primitive types. In C, derived data types include:

  • Arrays: A collection of elements of the same data type stored in contiguous memory locations.
  • Pointers: Variables that store the memory address of another variable.
  • Structures: Custom data types that group multiple variables of different data types.
  • Unions: Similar to structures but store different data types in the same memory location, allowing only one member to hold a value at any time.

Example of Derived Data Types

Let’s look at how each derived data type works with a simple example.

#include <stdio.h>

int main() {
    // Array example: storing multiple integers
    int numbers[3] = {1, 2, 3};
    printf("Array element 1: %d\n", numbers[0]);

    // Pointer example: storing the address of a variable
    int age = 30;
    int *agePtr = &age;  // pointer to the age variable
    printf("Age through pointer: %d\n", *agePtr);

    // Structure example: grouping related information
    struct Person {
        char name[50];
        int age;
    };
    struct Person person1 = {"Alice", 28};
    printf("Person Name: %s, Age: %d\n", person1.name, person1.age);

    // Union example: storing different data types in same memory location
    union Data {
        int intVal;
        float floatVal;
    };
    union Data data;
    data.intVal = 10;
    printf("Union integer value: %d\n", data.intVal);
    data.floatVal = 5.5;
    printf("Union float value (overwrites int): %.1f\n", data.floatVal);

    return 0;
}

Output:

Array element 1: 1
Age through pointer: 30
Person Name: Alice, Age: 28
Union integer value: 10
Union float value (overwrites int): 5.5

Explanation

  • Arrays (int numbers[3] = {1, 2, 3};) – This defines an array of integers with 3 elements. Accessing numbers[0] retrieves the first element, 1.
  • Pointers (int *agePtr = &age;) – Here, agePtr stores the address of age, and *agePtr dereferences the pointer to access the value of age.
  • Structures (struct Person person1 = {"Alice", 28};) – Person is a structure grouping a name and age together. This allows us to store both related attributes for each person in one unit.
  • Unions (union Data data;) – Unions store different data types in the same memory space, so only one member is valid at any time. Assigning intVal and then floatVal shows how the value is overwritten, displaying only the last assigned value.

What is Variable ?

A variable in C is a container that stores data. It has three key properties:

  1. Name: A unique identifier for the variable.
  2. Type: Specifies what type of data the variable holds.
  3. Value: The actual data stored in the variable.

Syntax for declaring Variables

data_type variable_name;
  • data_type: The type of data the variable will store (e.g., int, float, char).
  • variable_name: The name of the variable.

Example

int age;       // Declares an integer variable named age
float salary;  // Declares a float variable named salary
char grade;    // Declares a character variable named grade

Initializing variable

You can assign an initial value to a variable when you declare it.

int age = 25;      // Declare and initialize age with 25
float salary = 50000.50;  // Declare and initialize salary
char grade = 'A';  // Declare and initialize grade

Variable Naming Rules

Naming Rules (Syntax Rules)

  • Start with a letter or underscore: Variable names must start with a letter (a-z, A-Z) or an underscore (_). They cannot start with a digit.
    • int age;
    • float _height;
    • int 1stPlace; (invalid)
  • Only letters, digits, and underscores: Names can contain letters, digits, and underscores but no special characters like @, #, $, etc.
    • int score1;
    • float height@2; (invalid)
  • No reserved words: Variable names cannot be keywords (like int, float, return, etc.) as these have predefined meanings in C.
    • int for; (invalid)
  • Case-sensitive: Variable names are case-sensitive (total, Total, and TOTAL are different variables).
  • No whitespace: Variable names cannot contain spaces.
    • float student_score;
    • int student score; (invalid)

Naming Conventions (Best Practices)

  • Meaningful names: Choose descriptive names that explain the purpose of the variable, such as totalMarks, studentAge, or averageScore.
  • Camel case: Typically used in C to improve readability (e.g., studentAge, totalMarks).
  • Avoid single letters: Unless in specific contexts like loop counters (i, j) or temporary variables, single letters are usually discouraged.
  • Use underscores for separation: Underscores (_) can help separate words in names, especially for global variables or constants (total_marks, MAX_VALUE).

Examples of Valid and Invalid Variable Names

Variable NameValid or InvalidReason
age✅ ValidStarts with a letter.
_score✅ ValidStarts with an underscore.
2ndPlace❌ InvalidCannot start with a digit.
total_marks✅ ValidContains only letters, digits, and underscore.
student score❌ InvalidContains a space.
float❌ InvalidUses a reserved keyword.
averageHeight✅ ValidFollows camel case and is descriptive.
MAX_VALUE✅ ValidUses uppercase and underscores (typically for constants).

    Leave a Reply

    Your email address will not be published.

    Need Help?