Data Types in C

This tutorial explains the basics of data types in C. You will learn about their types, sizes, and uses. It also shows the difference between basic and advanced data types. You will see how data types affect memory use. Simple examples make it easy to understand.

Contents:

  1. What is Data Types in C?
  2. Types of Data Types in C
  3. Primary Data Types (Basic Data Types) in C
  4. Derived Data Types in C
  5. User-Defined Data Types in C
  6. Void Data Type (void) in C
  7. Size and Range of Data Types in C
  8. Type Modifiers in C
  9. Type Conversion in C
  10. FAQs on Data Types in C

What is Data Types in C?

In C programming, data types define the type and size of data that a variable can store. They determine how much memory will be allocated to a variable and what type of data it can hold.

Syntax:

data_type variable_name;

advertisement

Types of Data Types in C

C has three main categories of data types:

  • Primary Data Types (Basic Data Types)
  • Derived Data Types
  • User-Defined Data Types

Primary Data Types (Basic Data Types) in C

Primary data types, also known as basic data types, are the fundamental types that define the type of data a variable can hold. These data types specify the size, format, and range of values that a variable can store.

Types of Primary Data Types:

Free 30-Day Python Certification Bootcamp is Live. Join Now!
Data Type Description Example
int Integer (whole numbers) int age = 25;
float Floating-point numbers (decimals) float pi = 3.14;
double Double-precision floating-point double value = 99.99;
char Single character char grade = ‘A’;
void No value (used in functions) void function();

1. Integer (int)

  • Used to store whole numbers (both positive and negative).
  • Size: Typically 4 bytes (32 bits) on most systems.
  • Range: -2,147,483,648 to 2,147,483,647

Syntax:

int quizzes = 150;

2. float (Floating-Point Number)

  • Used to store decimal (fractional) numbers.
  • Size: 4 bytes (32 bits).
  • Precision: Stores up to 6 decimal places.

Syntax:

float avg_score = 92.75;

3. double (Double Precision Floating-Point Number)

  • Similar to float but provides double the precision.
  • Size: 8 bytes (64 bits).
  • Precision: Stores up to 15 decimal places.

Syntax:

double completion_time = 2.56789;

4. char (Character)

advertisement
  • Used to store a single character or ASCII value.
  • Size: 1 byte (8 bits).

Syntax:

char grade = 'A';

5. void (Empty Data Type)

  • Represents the absence of any value.
  • Typically used for functions that do not return a value.

Syntax:

void displayMessage()
{
    printf("Congratulations on completing the Sanfoundry Quiz!\n");
}

Example:

#include <stdio.h>
 
void displayMessage()
{
    printf("Congratulations on achieving success in Sanfoundry!\n");
}
 
int main()
{
    int quizzes = 150;               // Number of quizzes completed
    float avg_score = 92.75;         // Average quiz score
    double completion_time = 2.56789; // Certification completion time
    char grade = 'A';                // Quiz grade
 
    printf("Sanfoundry Quizzes Completed: %d\n", quizzes);
    printf("Average Quiz Score: %.2f\n", avg_score);
    printf("Time Taken to Complete Certification: %.5lf hours\n", completion_time);
    printf("Grade Achieved: %c\n", grade);
 
    displayMessage();
 
    return 0;
}

Output:

Sanfoundry Quizzes Completed: 150
Average Quiz Score: 92.75
Time Taken to Complete Certification: 2.56789 hours
Grade Achieved: A
Congratulations on achieving success in Sanfoundry!

Derived Data Types in C

Derived data types are built using primary (basic) data types. They provide more complex ways to store and manipulate data.

Derived Type Description Example
Array Collection of same-type elements int arr[5] = {1, 2, 3, 4, 5};
Pointer Stores memory address of a variable int *ptr = #
Function Block of reusable code int add(int, int);

1. Array

An array is a collection of elements of the same data type stored in contiguous memory locations. Elements in an array are accessed using an index starting from 0.

Syntax:

data_type array_name[size];

Example:

#include <stdio.h>
 
int main()
{
    // Array to store Sanfoundry quiz scores
    int scores[3] = {85, 90, 88};
 
    printf("Sanfoundry Quiz Scores: ");
    for (int i = 0; i < 3; i++) {
        printf("%d ", scores[i]);
    }
    return 0;
}

Output:

Sanfoundry Quiz Scores: 85 90 88

2. Pointers

A pointer is a variable that stores the address of another variable. It allows direct manipulation of memory addresses.

Syntax:

data_type *pointer_name;

Example:

#include <stdio.h>
 
int main()
{
    int score = 95;
    // Pointer storing the address of score
    int *ptr = &score;
 
    // Dereferencing pointer
    printf("Sanfoundry Score: %d\n", *ptr); 
    return 0;
}

Output:

Sanfoundry Score: 95

3. Function

A function in C is a derived data type that groups a set of statements to perform a specific task. It takes input, processes it, and may return a result.

Syntax:

return_type function_name(parameter_list)
{
    // Function body
}

Example:

#include <stdio.h>
 
// Function to calculate Sanfoundry Quiz Score
int calculateScore(int correct, int incorrect)
{
    // 4 marks for correct, -1 for wrong
    int score = (correct * 4) - (incorrect * 1);  
    return score;
}
 
int main() {
    int correct = 10, incorrect = 2;
 
    // Call the function and store the result
    int score = calculateScore(correct, incorrect);
 
    // Display the score
    printf("Final Sanfoundry Quiz Score: %d\n", score);
    return 0;
}

Output:

Final Sanfoundry Quiz Score: 38

User-Defined Data Types in C

User-defined data types in C allow the creation of custom data structures to model real-world objects and store different types of information.

Data Type Description Example
typedef Creates an alias for a data type typedef unsigned int uint;
struct Groups multiple variables of different types struct Student { char name[50]; int age; };
union Similar to struct, but shares memory union Data { int id; float salary; };
enum Defines named integer constants enum Day {SUNDAY, MONDAY, …};

1. Enumerations (enum)

An enumeration is a user-defined data type that assigns names to integral constants, making the code easier to read and maintain.

Syntax:

enum enum_name {constant1, constant2, ...};

Example:

#include <stdio.h>
 
// Define enum for Sanfoundry Quiz Levels
enum QuizLevel {BEGINNER, INTERMEDIATE, ADVANCED};
 
int main()
{
    enum QuizLevel level;
 
    // Assign and display level
    level = INTERMEDIATE;
    printf("Current Quiz Level: %d\n", level);  // Output will be 1
 
    return 0;
}

Output:

Current Quiz Level: 1

2. Typedef (typedef)

typedef is used to assign a new name to an existing data type to improve code readability.

Syntax:

typedef existing_type new_type_name;

Example:

#include <stdio.h>
 
// Define typedef for Sanfoundry ID
typedef unsigned int SanfoundryID;
 
int main()
{
    SanfoundryID id = 2025;
 
    printf("Sanfoundry ID: %u\n", id);
    return 0;
}

Output:

Sanfoundry ID: 2025

3. Structures

A structure is a user-defined data type that groups different types of data into a single unit.

Syntax:

struct structure_name
{
    data_type member1;
    data_type member2;
};

Example:

#include <stdio.h>
#include <string.h>
 
// Define structure for Sanfoundry quiz
struct SanfoundryQuiz
{
    int quizID;
    char topic[50];
    float score;
};
 
int main()
{
    struct SanfoundryQuiz quiz1;
 
    // Assign values to members
    quiz1.quizID = 101;
    strcpy(quiz1.topic, "C Programming");
    quiz1.score = 92.5;
 
    printf("Quiz ID: %d\n", quiz1.quizID);
    printf("Quiz Topic: %s\n", quiz1.topic);
    printf("Quiz Score: %.2f\n", quiz1.score);
 
    return 0;
}

Output:

Quiz ID: 101
Quiz Topic: C Programming
Quiz Score: 92.50

4. Unions

A union is a special data type where all members share the same memory location, allowing different data types to be stored in the same space.

Syntax:

union union_name
{
    data_type member1;
    data_type member2;
};

Example:

#include <stdio.h>
#include <string.h>
 
// Define union to store Sanfoundry results
union SanfoundryResult
{
    int quizScore;
    char certification[20];
};
 
int main()
{
    union SanfoundryResult result;
 
    // Assigning quiz score
    result.quizScore = 90;
    printf("Quiz Score: %d\n", result.quizScore);
 
    // Assigning certification status
    strcpy(result.certification, "Certified");
    printf("Certification: %s\n", result.certification);
 
    return 0;
}

Output:

Quiz Score: 90
Certification: Certified

Void Data Type (void) in C

The void data type in C is used to specify that a function does not return a value or to declare a pointer that can point to any data type. It essentially means “no value” or “no type.”

Uses of void in C:

  • Function with No Return Value
  • Void Pointers
  • Function with No Parameters

1. Function with No Return Value

Syntax:

void function_name(parameters);

Example:

#include <stdio.h>
 
// Function with void return type
void sanfoundryWelcome()
{
    printf("Welcome to Sanfoundry C Programming!\n");
}
 
int main()
{
    sanfoundryWelcome(); // Calling the function
    return 0;
}

Output:

Welcome to Sanfoundry C Programming!

2. Void Pointers

A void pointer can hold the address of any data type, making it a generic pointer.

Syntax:

void *pointer_name;

Example:

#include <stdio.h>
 
int main()
{
    int sanfoundryID = 1001;
    float sanfoundryScore = 95.5;
 
    // Void pointer declaration
    void *ptr;
 
    // Point to integer
    ptr = &sanfoundryID;
    printf("Sanfoundry ID: %d\n", *(int *)ptr);
 
    // Point to float
    ptr = &sanfoundryScore;
    printf("Sanfoundry Score: %.2f\n", *(float *)ptr);
 
    return 0;
}

Output:

Sanfoundry ID: 1001
Sanfoundry Score: 95.50

3. Function with No Parameters

When a function takes no arguments, void is used to indicate this.

Syntax:

void function_name(void);

Example:

#include <stdio.h>
 
// Function with void parameter
void display(void)
{
    printf("This function takes no parameters.\n");
}
 
int main()
{
    display();
    return 0;
}

Output:

This function takes no parameters.

Size and Range of Data Types in C

The size and range of data types in C depend on the system architecture (such as 32-bit or 64-bit) and the compiler being used. The sizeof() operator is used to determine the size of a data type in bytes.

Sizes and Ranges of Basic Data Types in C

Data Type Size (in bytes) Range
char 1 -128 to 127 (signed) or 0 to 255 (unsigned)
short int 2 -32,768 to 32,767
int 4 -2,147,483,648 to 2,147,483,647
long int 4 or 8 -2,147,483,648 to 2,147,483,647 (4 bytes) or larger
long long int 8 -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
float 4 3.4E-38 to 3.4E+38
double 8 1.7E-308 to 1.7E+308
long double 10, 12, or 16 3.4E-4932 to 1.1E+4932

1. Checking Size Using sizeof() Operator

sizeof(data_type);

2. Example: Size and Range of Data Types in C

#include <stdio.h>
#include <limits.h>
#include <float.h>
 
int main()
{
    // Displaying size and range of data types
    printf("Size of char: %lu bytes\n", sizeof(char));
    printf("Range of char: %d to %d\n", CHAR_MIN, CHAR_MAX);
 
    printf("\nSize of short int: %lu bytes\n", sizeof(short int));
    printf("Range of short int: %d to %d\n", SHRT_MIN, SHRT_MAX);
 
    printf("\nSize of int: %lu bytes\n", sizeof(int));
    printf("Range of int: %d to %d\n", INT_MIN, INT_MAX);
 
    printf("\nSize of long int: %lu bytes\n", sizeof(long int));
    printf("Range of long int: %ld to %ld\n", LONG_MIN, LONG_MAX);
 
    printf("\nSize of float: %lu bytes\n", sizeof(float));
    printf("Range of float: %.3e to %.3e\n", FLT_MIN, FLT_MAX);
 
    printf("\nSize of double: %lu bytes\n", sizeof(double));
    printf("Range of double: %.3e to %.3e\n", DBL_MIN, DBL_MAX);
 
    return 0;
}

Output:

Size of char: 1 bytes
Range of char: -128 to 127
 
Size of short int: 2 bytes
Range of short int: -32768 to 32767
 
Size of int: 4 bytes
Range of int: -2147483648 to 2147483647
 
Size of long int: 8 bytes
Range of long int: -9223372036854775808 to 9223372036854775807
 
Size of float: 4 bytes
Range of float: 1.175e-38 to 3.402e+38
 
Size of double: 8 bytes
Range of double: 2.225e-308 to 1.798e+308
  • sizeof() returns the size of a data type in bytes.
  • Header files like <limits.h> and <float.h> provide predefined macros for the minimum and maximum range of various data types.
  • The size of long int and long double may vary depending on the compiler and system architecture.

Type Modifiers in C

Type modifiers in C are used to alter the size, range, and type of data. They are applied to the primary data types to enhance the flexibility of data storage and processing.

Types of Type Modifiers:

  • Signed – Allows storing both positive and negative values.
  • Unsigned – Stores only positive values, extending the upper range.
  • Short – Reduces the storage size of an integer.
  • Long – Increases the storage size of an integer.

Syntax:

modifier data_type variable_name;

1. Signed Modifier

Allows both positive and negative values. (Default for int and char).

Example:

#include <stdio.h>
 
int main()
{
    signed int a = -100;
    signed char b = 'S';
 
    printf("Signed int value: %d\n", a);
    printf("Signed char value: %c\n", b);
 
    return 0;
}

Output:

Signed int value: -100
Signed char value: S

2. Unsigned Modifier

Stores only positive values, doubling the upper limit.

Example:

#include <stdio.h>
 
int main()
{
    unsigned int a = 500;
    unsigned char b = 255;
 
    printf("Unsigned int value: %u\n", a);
    printf("Unsigned char value: %u\n", b);
 
    return 0;
}

Output:

Unsigned int value: 500
Unsigned char value: 255

3. Short Modifier

Reduces the storage size of integers.

Example:

#include <stdio.h>
 
int main()
{
    short int a = 32767;
    printf("Short int value: %d\n", a);
 
    return 0;
}

Output:

Short int value: 32767

4. Long Modifier

Increases the memory size for integer and floating-point types.

Example:

#include <stdio.h>
 
int main()
{
    long int a = 100000L;
    printf("Long int value: %ld\n", a);
 
    return 0;
}

Output:

Long int value: 100000

Type Conversion in C

Type conversion in C refers to the process of converting one data type into another. It occurs in two ways:

  • Implicit Type Conversion (Type Promotion)
  • Explicit Type Conversion (Type Casting)

1. Implicit Type Conversion (Type Promotion)

Automatically performed by the compiler when operands of different types are mixed in an expression. Smaller data types are converted to larger data types to prevent data loss.

#include <stdio.h>
 
int main()
{
    int sanfoundryScore = 90;
    float bonusPoints = 4.5;
 
    // Implicit conversion: int to float
    float totalScore = sanfoundryScore + bonusPoints;
 
    printf("Sanfoundry Final Score: %.2f\n", totalScore);
 
    return 0;
}

Output:

Sanfoundry Final Score: 94.50

2. Explicit Type Conversion (Type Casting)

Also known as manual type conversion, it is done using the (type) operator.

#include <stdio.h>
 
int main()
{
    float sanfoundryRating = 9.8;
    int roundedRating;
 
    // Explicit conversion (Type Casting)
    roundedRating = (int)sanfoundryRating;
 
    printf("Original Sanfoundry Rating: %.1f\n", sanfoundryRating);
    printf("Rounded Sanfoundry Rating: %d\n", roundedRating);
 
    return 0;
}

Output:

Original Sanfoundry Rating: 9.8
Rounded Sanfoundry Rating: 9

FAQs on Data Types in C

1. What are data types in C?
Data types in C define the type of data that can be stored in a variable. They determine the size, range, and operations that can be performed on the data.

2. What is the void data type in C?
The void data type means “no type.” It is mainly used for functions that do not return a value and for generic pointers.

3. What are derived data types in C?
Derived data types are created from primary data types. Examples include arrays, pointers, and functions.

4. What is type conversion in C?
Type conversion changes a variable’s data type.

  • Implicit conversion happens automatically when a smaller type is converted into a larger one.
  • Explicit conversion (type casting) is done manually.

5. What is the difference between float and double in C?
float uses 4 bytes and has 6-7 decimal places precision, whereas double uses 8 bytes and has 15-16 decimal places precision.

6. What are user-defined data types in C?
These are custom data types created by users using structures (struct), unions (union), enumerations (enum), and type definitions (typedef).

7. What is the difference between signed and unsigned data types?
Signed types (default) can hold both positive and negative values, while unsigned types can only hold positive values.

Key Points to Remember

Here is the list of key points we need to remember about “Data Types in C”.

  • Data types in C define the type and size of data a variable can store, affecting memory allocation and usage.
  • C has three main categories of data types: Primary (Basic), Derived, and User-Defined.
  • Primary data types include int (integer), float (decimal), double (high-precision float), char (single character), and void (no value).
  • Derived data types are built from primary types, including arrays (collection of elements), pointers (memory addresses), and functions (code blocks that return values).
  • User-defined data types are created using struct (grouping multiple data types), union (memory-sharing structure), enum (named integer constants), and typedef (alias for existing data types).
  • Void data type is used in functions that return no value and for void pointers that can store any data type’s address.
  • The size of data types varies depending on the system architecture, with sizeof() used to determine memory usage. Headers <limits.h> and <float.h> provide predefined macros for data ranges.
  • Type modifiers like signed, unsigned, short, and long adjust the range and memory allocation of primary data types, providing flexibility in data storage.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.