Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
8 views

Modified C Programming Notes Updated

Uploaded by

amitkumar950925
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Modified C Programming Notes Updated

Uploaded by

amitkumar950925
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 77

C Programming Language Tutorial

Last Updated : 06 Jan, 2025




C is a general-purpose, procedural, and middle-


level programming language used for developing computer
software, system programming, applications, games, and
more. Known for its simplicity and efficiency, C is an excellent
choice for beginners as it provides a strong foundation in
programming concepts. C was developed by Dennis M. Ritchie at
Bell Laboratories in 1972. Initially, it was created for
programming the UNIX operating system.
 Bridges the gap between low-level programming (closer to

hardware and machine code) and high-level


programming (closer to human-readable code).
 Referred as the "mother of all programming

languages" because it influenced many modern programming


languages like C++, Java, Python and Go.
1
 C programs are platform-independent i.e. code can be
compiled and run on different systems with minimal
modifications.
 Does not require heavy runtime environments or libraries,

making it ideal for low-resource systems.


Hello World Program

#include <stdio.h>
2

3
int main()
4
{
5
printf("Hello World!");
6
return 0;
7
}
2
Output
Hello World!

In this C tutorial, we’ll cover everything from basic


syntax, data types, and control structures to advanced
topics like pointers, memory management, and file
handling. By the end, you’ll gain hands-on experience and a
solid understanding of C, which is essential for mastering other
programming languages like C++ and Java. Let’s dive into the
world of C programming and build a strong coding foundation!

C Overview
 What is C Language?
 C Features
 C Standards
 Setting Up C Development Environment
3
 Hello World Program
 Compiling a C Program: Behind the Scenes
C Basics
 Tokens
 Identifiers
 Keywords
 Comments
 Variables
 Constants
 Data Types
 Data Type Modifiers
 Type Conversion
 Operators
C Input/Output
 Basic Input and Output
 printf
 scanf
 Format Specifiers
 Escape Sequence
4
C Operators
 Arithmetic Operators
 Unary Operators
 Assignment Operators
 Logical Operators
 Bitwise Operator
 Signed Number Representation
 Operator Precedence and Associativity
C Flow Control
 if Statement
 if…else Statement
 if-else-if Ladder
 Switch Statement
 Using Range in Switch Case
 for Loop
 while looping
 do…while Loop
 continue Statement
 break Statement
5
 goto Statement
C Functions
 Introduction to Functions
 User-Defined Function
 Parameter Passing Techniques
 Main Function
 Inline Function
 Nested Functions
C Arrays
 Introduction to Arrays
 Length of Array
 Multidimensional Arrays
 Pass Array to Functions
 Pass a 2D Array as a Parameter
C Strings
 Introduction to Strings
 Length of String
 String Comparison
 String Copy
6
 String Concatenation
 Array of Strings
 String Functions
C Pointers
 Introduction to Pointers
 Pointer Arithmetics
 Pointer to Pointer (Double Pointer)
 Function Pointer
 Declare Function Pointer
 Pointer to an Array
 Constant Pointer
 Pointer vs Array
 Dangling, Void, Null and Wild Pointers
 Near, Far and Huge Pointers
 restrict Keyword
C Dynamic Memory Allocation
 Memory Structure of a Program
 Dynamic Memory Allocation (malloc(), calloc(), and free())
 Memory Leak
7
C Structures and Union
 Introduction to Structures
 Array of Structures
 Structure Pointer
 Structure Member Alignment
 Introduction to Unions
 Bit Fields
 Structure vs Union
 Anonymous Union and Structure
 Enumeration (or enum)
 dot (.) Operator
 typedef
C Storage Classes
 Introduction to Storage Classes
 extern Keyword
 Static Variables
 Initialization of Static Variables
 Static Functions
 Understanding “volatile” Qualifier
8
 Understanding the “register” Keyword
C Preprocessor
 Introduction to Preprocessors
 Preprocessor Directives
 How a Preprocessor Works?
 Header Files
 Header Files “stdio.h” vs “stdlib.h”
 Write Your Own Header File
 Macros and its Types
 Interesting Facts About Macros and Preprocessors
 # and ## Operators
 Print a Variable Name
 Multiline Macros
 Variable Length Arguments for Macros
 Branch Prediction Macros in GCC
 typedef versus #define
 Difference Between #define and const
C File Handling
 Basics of File Handling
9
 fopen() Function
 EOF, getc() and feof()
 fgets() and gets()
 fseek() vs rewind()
 Return Type of getchar(), fgetc() and getc()
 Read/Write Structure From/to a File
 Print Contents of File
 Delete a File
 Merge Contents of Two Files into a Third File
 printf vs sprintf vs fprintf
 getc() vs getchar() vs getch() vs getche()
C Error Handling
 Error Handling
 Using goto for Exception Handling
 Error Handling During File Operations
 Handle Divide By Zero and Multiple Exceptions
C Programs
 Basic C Programs
 Control Flow Programs
10
 Pattern Printing Programs
 Functions Programs
 Arrays Programs
 Strings Programs
 Conversions Programs
 Pointers Programs
 Structures and Unions Programs
 File I/O Programs
 Date and Time Programs
 More C Programs
Miscellaneous
 Date and Time
 Input-Output System Calls
 Signals
 Program Error Signals
 Socket Programming
 _Generics Keyword
 Multithreading
C Interview Questions
11
 Top 50 C Programming Interview Questions and Answers
 Commonly Asked C Programming Interview Questions | Set 1
 Commonly Asked C Programming Interview Questions | Set 2
 Commonly Asked C Programming Interview Questions | Set 3

C Overview

Open In App

Getting started with C


Last Updated : 01 Aug, 2023

12
C language is a popular programming language that was
developed in 1970 by Dennis Ritchie at Bell Labs. The C
programming language was developed primarily to build the
UNIX operating system. It is widely used because it is simple,
powerful, efficient, and portable.
Features of C Programming Language
The C programming language is rich in different types of
features. Some of them are:
1. Procedural Language: C is a procedural language
which means the flow of execution of each statement is
performed step by step.
2. Platform Independent: C is a portable Language which
means C programs written for one platform can be
compiled and executed on another platform with little or no
modification.
3. Fast Speed: C programming language is considered as
one of the fastest programming languages. C is a compiler-
based language so the program written in C language will
be the fastest to be compiled.
13
4. Low-Level Memory Management: C provides the
concept of pointers using which we can store the memory
addresses. It allows the low-level memory manipulation in
the language.
5. Easy to Learn: C is a simple programming language that
is easy to learn. Moreover, it also helps in learning other
languages due to the structural similarities.
C Tutorial
1. Introduction to C
Any programming language is best learned by writing
programs. As a tradition, we generally start programming by
writing the Hello World Program. After that, we study basic
language concepts and keep moving to the advanced concepts.
Refer to the article C Language Introduction to start learning C
Language.

14
2. Basic Syntax of C
The syntax of C programming language includes various rules
that define the structure of C language such as how to specify
statements, define functions, etc.
Refer to the article C Basic Syntax to learn the Syntax of the C
language in detail.
3. Variables and Data Types
A variable is a name associated with a memory location to store
data. A data type is the type of data a variable can store. Some
common data types in C are int, float, double, char, etc.
Refer to the article C Variables and Data Types in C for more
details learn Variables and Data types in detail.
4. Operators in C
Operators are the symbols that perform a specific operation to
be performed on the operands. C supports various operators
like arithmetic, relational, logical, assignment, etc.
Types of operators:
1. Arithmetic Operators
2. Relational Operators
15
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
6. Other Operators
Refer to the article Operators in C for more details.
5. Input and Output
Input means reading data from input devices or files. Output
means writing the data to the console or files. C Standard
Library provides various input and output functions. scanf() and
printf() are commonly used function.
Refer to the article Basic Input and Output in C to learn about
Input and Output methods in detail.
6. Conditional Statements
Conditional Statements are used to control the normal flow of
execution of the program. These statements are used to make
decisions whether to execute a specific block of code or not
based on the specific conditions.
The main decision-making statements in C are:
1. if Statements
16
2. If-else Statement
3. If-else-if Ladder
4. Nested If-else Statements
5. Conditional Operator
6. Switch-case Statements
Refer to the article Decision Making in C / C++ (if, if..else,
Nested if, if-else-if ) to learn Control Statements in detail.
7. Loops
In C, loops are used to repeatedly execute a block of code till a
given condition is true. Loops are also a part of control
statements just like conditional statements.
Types of Loops in C are:
1. For loop
2. while loop
3. do-while loop
Refer to article C – Loops to learn the concept of Loops in detail.
8. Functions
Functions are the block of code that is used to perform a
specific task. It is a set of statements enclosed within {} braces.
17
Functions make the code more readable and improve the
maintainability of the code.
Types of functions:
1. Predefined functions: The functions that are already
defined in the C Standard Library are predefined functions.
For example, printf() and scanf().
2. User-defined functions: The functions created by the
user to perform a specific task are the user-defined
functions.
Refer to the article C Functions for more details.
9. Pointers
In C, pointers are the variables that can store the address of
other variables, functions, structures, and even other pointers.
The pointer points to the memory location where the data is
actually stored. Using pointers we can access and manipulate
the data by directly accessing the memory where the data is
stored.
Refer to the article C Pointers to learn the concept of pointers in
detail.
18
10. Arrays
In C, Array is a way of storing multiple elements of the same
data type. Elements in an array are stored in contiguous
memory locations and each element in an array is accessed
using an index, which represents its position within the array.
Refer to the article C Arrays to learn Arrays in detail.
11. Strings
In C, a string is a sequence of characters enclosed within “”
double quotes. It is stored as an array of characters
terminated by a null character ‘\0’. For example,
“GeeksforGeeks”, “gfg”, etc are strings.
Refer to the article Strings in C to learn the concept of C Strings
in detail.
12. File Management
File management refers to the handling and manipulation of
files in the C programming language.

19
Following are the operations that can be performed on a
file:
1. Creation of a file.
2. Opening a file.
3. Reading the data from a file.
4. Writing data to a file.
5. Closing a file.
6. Getting the file position.
7. Deleting a file.
8. Renaming a file.
Refer to the article Basics of File Handling in C for more details
on File Management.

20
 C Basics
 Tokens
In C programming, tokens are the smallest units in a
program that have meaningful representations. Tokens
are the building blocks of a C program, and they are
recognized by the C compiler to form valid expressions
and statements. Tokens can be classified into various
categories, each with specific roles in the program.

Types of Tokens in C

21
Tokens-in-C
The tokens of C language can be classified into six
types based on the functions they are used to
perform. The types of C tokens are as follows:

Table of Content
Punctuators
Keywords
Strings
Operators
Identifiers
Constants
22
 Punctuators. The
following special symbols are used in C having
some special meaning and thus, cannot be used for
some other purpose. Some of these are listed
below:

 Brackets[]: Opening and closing brackets are


used as array element references. These indicate
single and multidimensional subscripts.
 Parentheses(): These special symbols are used to
indicate function calls and function parameters.
 Braces{}: These opening and ending curly
braces mark the start and end of a block of code
containing more than one executable statement.
23
 Comma (, ): It is used to separate more than one
statement like for separating parameters in function
calls.
 Colon(: It is an operator that essentially invokes
something called an initialization list.
 Semicolon(;): It is known as a statement
terminator. It indicates the end of one logical
entity. That’s why each individual statement must
be ended with a semicolon.
 Asterisk (*): It is used to create a pointer variable
and for the multiplication of variables.
 Assignment operator(=): It is used to assign
values and for logical operation validation.

24
 Pre-processor (#): The preprocessor is a macro
processor that is used automatically by the
compiler to transform your program before actual
compilation.
 Period (.): Used to access members of a structure
or union.
 Tilde(~): Bitwise One’s Complement Operator.
Example:
1
#include <stdio.h>
2
Int main() {
3
25
// ‘\n’ is a special symbol that
// represents a newline
6
Printf(“Hello, World!\n”);
7
Return 0;
8
}
Output
Hello, World!

 Keywords
26
Keywords are reserved words that have predefined
meanings in C. These cannot be used as identifiers
(variable names, function names, etc.). Keywords
define the structure and behavior of the program C
language supports 32 keywords some of them are:

Int, for, if, else, while, return, etc.


Example:
1
#include <stdio.h>
2
Int main() {
// ‘int’ is a keyword used to define
27
5
// variable type
6
Int x = 5;
7
Printf(“%d”, x);
// ‘return’ is a keyword used to exit
10
// main function
11
Return 0;
12
28
}
Output
5
Note: The number of keywords may change
depending on the version of C you are using. For
example, keywords present in ANSI C are 32 while in
C11, it was increased to 44. Moreover, in the latest
c23, it is increased to around 54.
3.Strings
Strings are nothing but an array of characters ended
with a null character (‘\0’). This null character
indicates the end of the string. Strings are always

29
enclosed in double quotes. Whereas a character is
enclosed in single quotes in C and C++.

Examples:
1
#include <stdio.h>
Int main() {
// “Hello, World!” is a string literal
Char str[] = “Hello, World!”;
Printf(“%s”, str);
Return 0;
}
30
Output
Hello, World!
4. Operators
Operators are symbols that trigger an action when
applied to C variables and other objects. The data
items on which operators act are called operands.
Depending on the number of operands that an
operator can act upon, operators can be classified as
follows:
 Unary Operators: Those operators that require
only a single operand to act upon are known as
unary operators.For Example increment and
decrement operators
31
 Binary Operators: Those operators that require
two operands to act upon are called binary
operators. Binary operators can further are
classified into:
Arithmetic operators
Relational Operators
Logical Operators
Assignment Operators
Bitwise Operator
Ternary Operator: The operator that requires three
operands to act upon is called the ternary operator.
Conditional Operator(?) is also called the ternary
operator.
32
Example:
#include <stdio.h>
Int main() {
Int a = 10, b = 5;
// ‘+’ is an arithmetic operator used
// for addition
Int sum = a + b;
Printf(“%d”, sum);
Return 0;
}
Output
15
33
5. Identifiers
Identifiers are names given to variables, functions,
arrays, and other user-defined items. They must begin
with a letter (a-z, A-Z) or an underscore (_) and can be
followed by letters, digits (0-9), and underscores.
Example:
#include <stdio.h>
Int main() {
// ‘num’ is an identifier used to name
// a variable
Int num = 10;
Printf(“%d”, num);

34
Return 0;}
Output
10
6. Constants
Constants are fixed values used in a C program. These
values do not change during the execution of the
program. Constants can be integers, floating-point
numbers, characters, or strings.
Examples:
#include <stdio.h>
Int main() {
// ‘MAX_VALUE’ is a constant that holds

35
// a fixed value
Const int MAX_VALUE = 100;
Printf(“%d”, MAX_VALUE);
Return 0;
}. Output. Will be 100

C Identifiers
Last Updated : 20 Jan, 2025
In C programming, identifiers are the names used to
identify variables, functions, arrays, structures, or any
other user-defined items. It is a name that uniquely
identifies a program element and can be used to refer
to it later in the program.

Example:
36
// Creating a variable
Int val = 10;

// Creating a function
Void func() {}
In the above code snippet, “val” and “func” are
identifiers.

Rules for Naming Identifiers in C


A programmer must follow a set of rules to create an
identifier in C:

Identifier can contain following characters:


Uppercase (A-Z) and lowercase (a-z) alphabets.
37
Numeric digits (0-9).
Underscore (_).
The first character of an identifier must be a letter or
an underscore.
Identifiers are case-sensitive.
Identifiers cannot be keywords in C (such as int,
return, if, while etc.).

Keywords vs Identifiers

38
Feature Keyword Identifier
Definition A keyword is a An identifier is a
reserved word user-defined
with a special name used to
meaning in C refer to
that cannot be variables,
used as an functions, arrays,
identifier. etc.
Usage Keywords are Identifiers are
predefined in the used by
C language and programmers to
are used to name variables,
define the functions, and
structure and other user-
control flow of defined elements
the program (e.g., age, sum,
(e.g., int, if, main).
while).
39
Example Int, return, for, if, totalAmount,
while studentAge,
Keywords in C
Last Updated : 10 Jan, 2025
In C Programming language, there are many rules so
to avoid different types of errors. One of such rule is
not able to declare variable names with auto, long,
etc. This is all because these are keywords. Let us
check all keywords in C language.
What are Keywords?
Keywords are predefined or reserved words that have
special meanings to the compiler. These are part of
the syntax and cannot be used as identifiers in the
program. A list of keywords in C or reserved words in
the C programming language are mentioned below:
40
Examples:
Auto Break Case Char Const Continue Default
Do Double Else Enum Extern Float For
Goto If Int Long Register. Return Short
Signed Sizeof Static Struct Switch Typedef
Union Unsigned Void Volatile
Conclusion
1. In this article, the points we learned about the
keywords are mentioned below:
2. Keywords are Reserved words in C with certain
meanings.
3. We can’t use keywords as any element’s
name.

41
4. There are 32 keywords in C all having unique
meanings.

C Comments
Last Updated : 17 Jan, 2025
The comments in C are human-readable explanations
or notes in the source code of a C program.
A comment makes the program easier to read and
understand. These are the statements that are not
executed by the compiler or an interpreter.
Example:
#include <stdio.h>
Int main()
42
{
// This is a comment, the below statement will not
be executed
// printf(“Hi from comment”);
Printf(“Hello”);
Return 0;
}
Output Hello

In C there are two types of comments in C


language:
Table of Content.
43
Single-line Comments
Multi-line Comments
1.Single-line Comments
Single-line comments are used to comment out a
single line of code or a part of it. These comments
start with two forward slashes (//), and everything
after the slashes on that line is considered a comment.
They are also called C++ Style comments as they
were first introduced in C++ and later adopted in C
also.
Syntax:
// This is a single line comment
Example:
44
#include <stdio.h>
Int main() {
// This is a single-line comment explaining the
variable x
Int x = 5;
// Output the value of x
Printf(“Value of x: %d\n”, x);
Return 0;
}
Output

45
Value of x: 5. (In this example, the comments
provide explanations about the code. The compiler
ignores the comments and does not execute them.)
We can also create a comment that displays at the
end of a line of code using a single-line comment. But
generally, it’s better to practice putting the comment
before the line of code.
Example:
#include <stdio.h>
Int main() {
// single line comment here
Printf(“Hi”); // After line comment here
Return 0;
46
}
Output
Welcome to GeeksforGeeks
Multi-line Comments
Multi-line comments are used for longer descriptions
or for commenting out multiple lines of code. These
comments begin with /* and end with */. Everything
between these markers is treated as a comment.
Syntax:
/* This is a multi-line comment
Which can span multiple lines */
Example:
47
#include <stdio.h>
Int main() {
/*This comment contains some code which Will not be
executed.
Printf(“Code enclosed in Comment”);
*/
Printf(“Welcome to GeeksforGeeks”);
Return 0;
}
Output
Welcome to GeeksforGeeks
Nesting Comments
48
In C, comments cannot be nested. That means you
cannot place a multi-line comment inside another
multi-line comment. If you try to do so, the compiler
will treat the closing */ of the inner comment as the
end of the entire multi-line comment.
Best Practices for Writing Comments
 Following are some best practices to write
comments in your program:
Write comments that are easy to understand.
Do not comment on every line unnecessarily
and avoid writing obvious comments.
Update comments regularly.

49
Focus on explaining the intent behind the
code rather than restating the obvious.

C Variables
Last Updated : 21 Jan, 2025
In C, variable is a name given to the memory location
that helps us to store some form of data and retrieves
it when required. It allows us to refer to memory
location without having to memorize the memory
address. A variable name can be used in expressions
as a substitute in place of the value it stores.
Example:
50
#include <stdio.h>
Int main() {
// Declaring variables
Int a;
// Storing data / initializing ‘a’ with 25.
a = 25;
Printf(“%d”, a);
Return 0;
}
Output
25

51
Explanation: In the given program, a is a variable
that serves as a name for a memory location to store
an integer value. It store the value 25 and later
retrieve it for printing without needing to reference its
full memory address.
In C, we have to declare the type of data the variable
would store along with the name while creating a
variable:
Syntax : Data_type variable_name;
This data_type decides how much memory a variable
need. We can choose the data types provided by C
language to store different type of data in the variable.

52
We can also create multiple variables in a single
statement by separating them using comma:
Data_type v1, v2, v3 ….;
Where v1, v2 … are the names for variables.
Example:
Int var; // integer variable
Char a; // character variable
Float fff; // float variable

The above syntax is called variable definition. In this, a


variable is only named and allocated some memory to
it. No data is stored in it till now.

53
The data is first entered in the variable in the process
called variable initialization. It is nothing but assigning
some initial value to it using assignment operator (=).
Variable_name = value;
It can also be combined with variable definition:
Data_type variable_name; = value;
Rules for Naming Variables in C

54
We can assign any name to the variable as long as it
follows the following rules:

1. A variable name must only contain alphabets,


digits, and underscore.
2. A variable name must start with an alphabet
or an underscore only. It cannot start with a digit.
3. No white space is allowed within the variable
name.
4. A variable name must not be any reserved
word or keyword.

55
Constants in C
Last Updated : 04 Feb, 2025
In C programming, constants are read-only values that
cannot be modified during the execution of a program.
These constants can be of various types, such as
integer, floating-point, string, or character constants.
They are initialized with the declaration and remain
same till the end of the program.
Let’s take a look at an example:
#include <stdio.h>

56
Int main() {
// Defining constant variable
Const a = 10;
Printf(“%d”, a);
Return 0;.}
Output 10
Explanation: In the above program, we created a
constant variable a with value 22. This value cannot
be modified later in the program.
Syntax
We define a constant in C using the const keyword.
Also known as a const type qualifier, the const

57
keyword is placed at the start of the variable
declaration to declare that variable as a constant.
Syntax: Const data_type var_name = value;
Syntax-of-constants-in-c
Properties of Constant
The important properties of constant variables in C
defined using the const keyword are as follows:
1. Initialization with Declaration
We can only initialize the constant variable in C at the
time of its declaration. If we do not initialize it at the
time of declaration, it will store the garbage value that
was previously stored in the same memory.
#include <stdio.h>
58
Int main() {
// Not initializing a constant variable
Const int a;
// printing value
Printf(“%d”, a);
Return 0; }

: Output 0
The garbage value here is 0 but I can by anything
depending on your environment.
2. Immutability
The constant variables in c are immutable after its
definition, i.e., they can be initialized only once in the
59
whole program. After that, we cannot modify the value
stored inside that variable.

#include <stdio.h>
Int main() {
// Declaring a constant variable
Const int a;
// Initializing constant variable var after declaration
A = 20;
Printf(“%d”, a);
Return 0; }
60
Output
In function ‘main’:
10:9: error: assignment of read-only variable ‘a’
10 | a = 20;
| ^

Constants Using #define


In C, the #define directive can also be used to define
symbolic constants that do not require a data type.

61
They are called macros and are replaced by their
values at compile time.
Syntax:
#define CONSTANT_NAME value
Example:
#include <stdio.h>
#define PI 3.14
Int main() {
Printf(“%.2f”, PI);
Return 0;
}
Output
62
3.14
Explanation: In this example, the value 3.14 is
replaced by PI during the compilation.
Difference Between Constants and Literals
The constant and literals are often confused as the
same. But in C language, they are different entities
and have different semantics. The following table lists
the differences between the constants and literals in
C:

63
Constant Literals
Constants are variables Literals are the fixed
that cannot be modified values that define
once declared. themselves
Constants are defined by They themselves are the
using the const keyword values that are assigned
in C. They store literal to the variables or
values in themselves. constants.
We can determine the We cannot determine the
address of constants. address of a literal except
string literal.
They are lvalues They are rvalue
Example: const int c = 20. Example: 24,15.5, ‘a’,
“Geeks”, etc.

Const vs #define
64
Constant using const Constant using #define
They are the variables They are the macros that
that are immutable are replaced by their
value.
They are handled by the They are handled by the
compiler. preprocessor
Syntax: Syntax:
const type name = value; #define name value

Data Types in C
65
Last Updated : 10 Jan, 2025
Each variable in C has an associated data type. It
specifies the type of data that the variable can store
like integer, character, floating, double, etc. Each data
type requires different amounts of memory and has
some specific operations which can be performed over
it.
The data types in C can be classified as follows:
Type Description Datatype
Primitive Primitive data types are the Int, char,
data type most basic data types that float,
are used for representing double, void
simple values such as
integers, float, characters,
66
etc.
Derived The data types that are Array,
data type derived from the primitive pointers,
or built-in datatypes are function
referred to as Derived Data
Types.
User The user-defined data types Structure,
defined are defined by the user union, enum
data type himself.

Understanding C’s data types is critical for writing


efficient programs.
The following are some main primitive data types in C:
Table of Content
Integer Data Type
67
Character Data Type
Float Data Type
Double Data Type
Void Data Type
1. Integer Data Type
The integer datatype in C is used to store the integer
numbers (any number including positive, negative and
zero without decimal part). Octal values, hexadecimal
values, and decimal values can be stored in int data
type in C.

Range: -2,147,483,648 to 2,147,483,647


Size: 4 bytes
68
Format Specifier: %d
Syntax of Integer
We use int keyword to declare the integer variable:
Int var_name;
The integer data type can also be used as
Unsigned int: Unsigned int data type in C is used to
store the data values from zero to positive numbers
but it can’t store negative values like signed int.
Short int: It is lesser in size than the int by 2 bytes so
can only store values from -32,768 to 32,767.
Long int: Larger version of the int datatype so can
store values greater than int.

69
Unsigned short int: Similar in relationship with short
int as unsigned int with int.
Note: The size of an integer data type is compiler-
dependent. We can use sizeof operator to check the
actual size of any data type.
2. Character Data Type
Character data type allows its variable to store only a
single character. The size of the character is 1 byte. It
is the most basic data type in C. It stores a single
character and requires a single byte of memory in
almost all compilers.

Range: (-128 to 127) or (0 to 255)


70
Size: 1 byte
Format Specifier: %c
Syntax of char
The char keyword is used to declare the variable of
character type: Char var_name;
3. Float Data Type
In C programming float data type is used to store
floating-point values. Float in C is used to store
decimal and exponential values. It is used to store
decimal numbers (numbers with floating point values)
with single precision.
Range: 1.2E-38 to 3.4E+38
Size: 4 bytes
71
Format Specifier: %f
Syntax of float
The float keyword is used to declare the variable as a
floating point:
Float var_name;

4. Double Data Type


A Double data type in C is used to store decimal
numbers (numbers with floating point values) with
double precision. It is used to define numeric values
which hold numbers with decimal values in C.

72
The double data type is basically a precision sort of
data type that is capable of holding 64 bits of decimal
numbers or floating points. Since double has more
precision as compared to that float then it is much
more obvious that it occupies twice the memory
occupied by the floating-point type. It can easily
accommodate about 16 to 17 digits after or before a
decimal point.
Range: 1.7E-308 to 1.7E+308
Size: 8 bytes
Format Specifier: %lf
Syntax of Double

73
The variable can be declared as double precision
floating point using the double keyword:
Double var_name;
5. Void Data Type
The void data type in C is used to specify that no value
is present. It does not provide a result value to its
caller. It has no values and no operations. It is used to
represent nothing. Void is used in multiple ways as
function return type, function arguments as void, and
pointers to void.
Syntax:
// function return type void
Void exit(int check);

74
// Function without any parameter can accept void.
Int print(void);
// memory allocation function which
// returns a pointer to void.
Void *malloc (size_t size);

Size of Data Types in C


The size of the data types in C is dependent on the
size of the architecture, so we cannot define the
universal size of the data types. For that, the C
language provides the sizeof() operator to check the
size of the data types.
Different data types also have different ranges up to
which they can store numbers. These ranges may vary
from compiler to compiler. Below is a list of ranges
75
along with the memory requirement and format
specifiers on the 32-bit GCC compiler.

76
Data Types in C: Size, Range, and Format Specifiers
Each data type in C has a specific size, range, and format specifier that determines how it is stored in memory and
how it is displayed in output.

Data Type Size (bytes) Range Format Specifier


char 1 byte -128 to 127 (signed) %c
0 to 255 (unsigned)
short 2 bytes -32,768 to 32,767 (signed) %hd
0 to 65,535 (unsigned)
int 4 bytes -2,147,483,648 to %d (signed)
2,147,483,647 (signed) %u (unsigned)
0 to 4,294,967,295
(unsigned)
long 4 or 8 bytes -2,147,483,648 to %ld
2,147,483,647 (32-bit)
-
9,223,372,036,854,775,808
to
9,223,372,036,854,775,807
(64-bit)
long long 8 bytes - %lld
9,223,372,036,854,775,808
to
9,223,372,036,854,775,807
float 4 bytes ±3.4E-38 to ±3.4E+38 %f
double 8 bytes ±1.7E-308 to ±1.7E+308 %lf
long double 12 or 16 bytes ±3.4E-4932 to ±1.1E+4932 %Lf
void 0 bytes No data storage N/A

77

You might also like