Structure Member Alignment, Padding and Data Packing
Last Updated :
10 Jan, 2025
In C, the structures are used as data packs. They don’t provide any data encapsulation or data hiding features.
In this article, we will discuss the property of structure padding in C along with data alignment and structure packing.
Data Alignment in Memory
Every data type in C will have alignment requirements (in fact it is mandated by processor architecture, not by language). A processor will have processing word length as that of data bus size. On a 32-bit machine, the processing word size will be 4 bytes.
Historically memory is byte addressable and arranged sequentially. If the memory is arranged as a single bank of one-byte width, the processor needs to issue 4 memory read cycles to fetch an integer. It is more economical to read all 4 bytes of an integer in one memory cycle. To take such advantage, the memory will be arranged as a group of 4 banks as shown in the above figure.
The memory addressing still be sequential. If bank 0 occupies an address X, bank 1, bank 2 and bank 3 will be at (X + 1), (X + 2), and (X + 3) addresses. If an integer of 4 bytes is allocated on X address (X is a multiple of 4), the processor needs only one memory cycle to read the entire integer. Whereas, if the integer is allocated at an address other than a multiple of 4, it spans across two rows of the banks as shown in the below figure. Such an integer requires two memory read cycles to fetch the data.

A variable’s data alignment deals with the way the data is stored in these banks. For example, the natural alignment of int on a 32-bit machine is 4 bytes. When a data type is naturally aligned, the CPU fetches it in minimum read cycles.
Similarly, the natural alignment of a short int is 2 bytes. It means a short int can be stored in bank 0 – bank 1 pair or bank 2 – bank 3 pair. A double requires 8 bytes and occupies two rows in the memory banks. Any misalignment of double will force more than two read cycles to fetch double data.
Note that a double variable will be allocated on an 8-byte boundary on a 32-bit machine and requires two memory read cycles. On a 64-bit machine, based on a number of banks, a double variable will be allocated on the 8-byte boundary and requires only one memory read cycle.
Structure Padding in C
Structure padding is the addition of some empty bytes of memory in the structure to naturally align the data members in the memory. It is done to minimize the CPU read cycles to retrieve different data members in the structure.
Try to calculate the size of the following structures:
C
// structure A
typedef struct structa_tag {
char c;
short int s;
} structa_t;
// structure B
typedef struct structb_tag {
short int s;
char c;
int i;
} structb_t;
// structure C
typedef struct structc_tag {
char c;
double d;
int s;
} structc_t;
// structure D
typedef struct structd_tag {
double d;
int s;
char c;
} structd_t;
Calculating the size of each structure by directly adding the size of all the members, we get:
- Size of Structure A = Size of (char + short int) = 1 + 2 = 3.
- Size of Structure B = Size of (short int + char + int) = 2 + 1 + 4 = 7.
- Size of Structure C = Size of (char + double + int) = 1 + 8 + 4 = 13.
- Size of Structure A = Size of (double + int + char) = 8 + 4 + 1= 13.
Now let’s confirm the size of these structures using the given C Program:
c
// C Program to demonstrate the structure padding property
#include <stdio.h>
// Alignment requirements
// (typical 32 bit machine)
// char 1 byte
// short int 2 bytes
// int 4 bytes
// double 8 bytes
// structure A
typedef struct structa_tag {
char c;
short int s;
} structa_t;
// structure B
typedef struct structb_tag {
short int s;
char c;
int i;
} structb_t;
// structure C
typedef struct structc_tag {
char c;
double d;
int s;
} structc_t;
// structure D
typedef struct structd_tag {
double d;
int s;
char c;
} structd_t;
int main()
{
printf("sizeof(structa_t) = %lu\n", sizeof(structa_t));
printf("sizeof(structb_t) = %lu\n", sizeof(structb_t));
printf("sizeof(structc_t) = %lu\n", sizeof(structc_t));
printf("sizeof(structd_t) = %lu\n", sizeof(structd_t));
return 0;
}
Outputsizeof(structa_t) = 4
sizeof(structb_t) = 8
sizeof(structc_t) = 24
sizeof(structd_t) = 16
As we can see, the size of the structures is different from those we calculated.
This is because of the alignment requirements of various data types, every member of the structure should be naturally aligned. The members of the structure are allocated sequentially in increasing order.
Let us analyze each struct declared in the above program. For the sake of convenience, assume every structure type variable is allocated on a 4-byte boundary (say 0x0000), i.e. the base address of the structure is multiple of 4 (need not necessarily always, see an explanation of structc_t).
Structure A
The structa_t first element is char which is one byte aligned, followed by short int. short int is 2 bytes aligned. If the short int element is immediately allocated after the char element, it will start at an odd address boundary. The compiler will insert a padding byte after the char to ensure short int will have an address multiple of 2 (i.e. 2 byte aligned). The total size of structa_t will be,
sizeof(char) + 1 (padding) + sizeof(short), 1 + 1 + 2 = 4 bytes.
Structure B
The first member of structb_t is short int followed by char. Since char can be on any byte boundary no padding is required between short int and char, in total, they occupy 3 bytes. The next member is int. If the int is allocated immediately, it will start at an odd byte boundary. We need 1-byte padding after the char member to make the address of the next int member 4-byte aligned. On total,
the structb_t requires , 2 + 1 + 1 (padding) + 4 = 8 bytes.
Structure C – Every structure will also have alignment requirements
Applying same analysis, structc_t needs sizeof(char) + 7-byte padding + sizeof(double) + sizeof(int) = 1 + 7 + 8 + 4 = 20 bytes. However, the sizeof(structc_t) is 24 bytes. It is because, along with structure members, structure type variables will also have natural alignment. Let us understand it by an example. Say, we declared an array of structc_t as shown below
structc_t structc_array[3];
Assume, the base address of structc_array is 0x0000 for easy calculations. If the structc_t occupies 20 (0x14) bytes as we calculated, the second structc_t array element (indexed at 1) will be at 0x0000 + 0x0014 = 0x0014. It is the start address of the index 1 element of the array. The double member of this structc_t will be allocated on 0x0014 + 0x1 + 0x7 = 0x001C (decimal 28) which is not multiple of 8 and conflicts with the alignment requirements of double. As we mentioned at the top, the alignment requirement of double is 8 bytes.
In order to avoid such misalignment, the compiler introduces alignment requirements to every structure. It will be as that of the largest member of the structure. In our case alignment of structa_t is 2, structb_t is 4 and structc_t is 8. If we need nested structures, the size of the largest inner structure will be the alignment of an immediate larger structure.
In structc_t of the above program, there will be a padding of 4 bytes after the int member to make the structure size multiple of its alignment. Thus the size of (structc_t) is 24 bytes. It guarantees correct alignment even in arrays.
Structure D
In a similar way, the size of the structure D is :
sizeof(double) + sizeof(int) + sizeof(char) + padding(3) = 8 + 4 + 1 + 3 = 16 bytes
How to Reduce Structure Padding?
By now, it may be clear that padding is unavoidable. There is a way to minimize padding. The programmer should declare the structure members in their increasing/decreasing order of size. An example is structd_t given in our code, whose size is 16 bytes in lieu of 24 bytes of structc_t.
What is Structure Packing?
Sometimes it is mandatory to avoid padded bytes among the members of the structure. For example, reading contents of ELF file header or BMP or JPEG file header. We need to define a structure similar to that of the header layout and map it. However, care should be exercised in accessing such members. Typically reading byte by byte is an option to avoid misaligned exceptions but there will be a hit on performance.
Most of the compilers provide nonstandard extensions to switch off the default padding like pragmas or command line switches. Consult the documentation of the respective compiler for more details.
In GCC, we can use the following code for structure packing:
#pragma pack(1)
or
struct name {
...
}__attribute__((packed));Example of Structure Packing
C
// C Program to demonstrate the structure packing
#include <stdio.h>
#pragma pack(1)
// structure A
typedef struct structa_tag {
char c;
short int s;
} structa_t;
// structure B
typedef struct structb_tag {
short int s;
char c;
int i;
} structb_t;
// structure C
typedef struct structc_tag {
char c;
double d;
int s;
} structc_t;
// structure D
typedef struct structd_tag {
double d;
int s;
char c;
} structd_t;
int main()
{
printf("sizeof(structa_t) = %lu\n", sizeof(structa_t));
printf("sizeof(structb_t) = %lu\n", sizeof(structb_t));
printf("sizeof(structc_t) = %lu\n", sizeof(structc_t));
printf("sizeof(structd_t) = %lu\n", sizeof(structd_t));
return 0;
}
Outputsizeof(structa_t) = 3
sizeof(structb_t) = 7
sizeof(structc_t) = 13
sizeof(structd_t) = 13
Structure Member Alignment, Padding and Data Packing – FAQs
Is alignment applied for stack?
Yes. The stack is also memory. The system programmer should load the stack pointer with a memory address that is properly aligned. Generally, the processor won’t check stack alignment, it is the programmer’s responsibility to ensure proper alignment of stack memory. Any misalignment will cause run-time surprises.
For example, if the processor word length is 32-bit, the stack pointer also should be aligned to be a multiple of 4 bytes.
If char data is placed in a bank other than bank 0, it will be placed on the wrong data lines during memory reading. How the processor handles char type?
Usually, the processor will recognize the data type based on instruction (e.g. LDRB on an ARM processor). Depending on the bank it is stored, the processor shifts the byte onto the least significant data lines.
When arguments are passed on the stack, are they subjected to alignment?
Yes. The compiler helps the programmer in making proper alignment. For example, if a 16-bit value is pushed onto a 32-bit wide stack, the value is automatically padded with zeros out to 32 bits. Consider the following program.
c
void argument_alignment_check( char c1, char c2 )
{
// Considering downward stack
// (on upward stack the output will be negative)
printf("Displacement %d\n", (int)&c2 - (int)&c1);
}
The output will be 4 on a 32-bit machine. It is because each character occupies 4 bytes due to alignment requirements.
What will happen if we try to access misaligned data?
It depends on the processor architecture. If the access is misaligned, the processor automatically issues sufficient memory read cycles and packs the data properly onto the data bus. The penalty is on performance. Whereas few processors will not have the last two address lines, which means there is no way to access the odd byte boundary. Every data access must be aligned (4 bytes) properly. Misaligned access is a critical exception on such processors. If the exception is ignored, read data will be incorrect and hence the results.
Is there any way to query the alignment requirements of a data type?
Yes. Compilers provide non-standard extensions for such needs. For example, __alignof() in Visual Studio helps in getting the alignment requirements of data type. Read MSDN for details.
When memory reading is efficient in reading 4 bytes at a time on a 32-bit machine, why should a double type be aligned on an 8-byte boundary?
It is important to note that most of the processors will have a math co-processor, called Floating Point Unit (FPU). Any floating point operation in the code will be translated into FPU instructions. The main processor is nothing to do with floating-point execution. All this will be done behind the scenes.
As per standard, the double type will occupy 8 bytes. And, every floating point operation performed in FPU will be of 64-bit length. Even float types will be promoted to 64 bits prior to execution.
The 64-bit length of FPU registers forces double type to be allocated on an 8-byte boundary. I am assuming (I don’t have concrete information) in the case of FPU operations, data fetch might be different, I mean the data bus since it goes to FPU. Hence, the address decoding will be different for double types (which are expected to be on an 8-byte boundary). It means the address decoding circuits of the floating point unit will not have the last 3 pins.
This article is contributed by Venki.
Master C programming with our C Programming Course Online, which covers everything from the basics to advanced concepts like data structures. Gain a deep understanding of C and enhance your problem-solving abilities with practical coding challenges.
Take the Three 90 Challenge! Complete 90% of the course in 90 days, and earn a 90% refund. Track your learning journey and get rewarded for your commitment.
Join now and start mastering C programming!
Similar Reads
C Programming Language Tutorial
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 concep
6 min read
C Basics
C Language Introduction
C is a procedural programming language initially developed by Dennis Ritchie in the year 1972 at Bell Laboratories of AT&T Labs. It was mainly developed as a system programming language to write the UNIX operating system. The main features of the C language include: General Purpose and PortableL
6 min read
Features of C Programming Language
C is a procedural programming language. It was initially developed by Dennis Ritchie in the year 1972. It was mainly developed as a system programming language to write an operating system. The main features of C language include low-level access to memory, a simple set of keywords, and a clean styl
3 min read
C Programming Language Standard
Introduction:The C programming language has several standard versions, with the most commonly used ones being C89/C90, C99, C11, and C18. C89/C90 (ANSI C or ISO C) was the first standardized version of the language, released in 1989 and 1990, respectively. This standard introduced many of the featur
6 min read
C Hello World Program
The “Hello World” program is the first step towards learning any programming language and also one of the simplest programs you will learn. To print the "Hello World", we can use the printf function from the stdio.h library that prints the given string on the screen. C Program to Print "Hello World"
2 min read
Compiling a C Program: Behind the Scenes
The compilation is the process of converting the source code of the C language into machine code. As C is a mid-level language, it needs a compiler to convert it into an executable code so that the program can be run on our machine. The C program goes through the following phases during compilation:
4 min read
C Comments
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. It is considered to be a good practice to document our code using
3 min read
Tokens in C
A token in C can be defined as the smallest individual element of the C programming language that is meaningful to the compiler. It is the basic component of a C program. Types of Tokens in CThe tokens of C language can be classified into six types based on the functions they are used to perform. Th
5 min read
Keywords in C
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 w
13 min read
C Variables and Constants
C Variables
A variable in C language is the name associated with some memory location to store data of different types. There are many types of variables in C depending on the scope, storage class, lifetime, type of data they store, etc. A variable is the basic building block of a C program that can be used in
9 min read
Constants in C
The constants in C are the read-only variables whose values cannot be modified once they are declared in the C program. The type of constant can be an integer constant, a floating pointer constant, a string constant, or a character constant. In C language, the const keyword is used to define the con
6 min read
Const Qualifier in C
The qualifier const can be applied to the declaration of any variable to specify that its value will not be changed (which depends upon where const variables are stored, we may change the value of the const variable by using a pointer). The result is implementation-defined if an attempt is made to c
6 min read
Different ways to declare variable as constant in C
There are many different ways to make the variable as constant in C. Some of the popular ones are: Using const KeywordUsing MacrosUsing enum Keyword1. Using const KeywordThe const keyword specifies that a variable or object value is constant and can't be modified at the compilation time. Syntaxconst
2 min read
Scope rules in C
The scope of a variable in C is the block or the region in the program where a variable is declared, defined, and used. Outside this region, we cannot access the variable, and it is treated as an undeclared identifier. The scope is the area under which a variable is visible.The scope of an identifie
6 min read
Internal Linkage and External Linkage in C
In C, linkage is a concept that describes how names/identifiers can or cannot refer to the same entity throughout the whole program or a single translation unit. The above sounds similar to scope, but it is not so. To understand what the above means, let us dig deeper into the compilation process. B
5 min read
Global Variables in C
Prerequisite: Variables in C In a programming language, each variable has a particular scope attached to them. The scope is either local or global. This article will go through global variables, their advantages, and their properties. The Declaration of a global variable is very similar to that of a
3 min read
C Data Types
Data Types in C
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 cl
7 min read
Literals in C
In C, Literals are the constant values that are assigned to the variables. Literals represent fixed values that cannot be modified. Literals contain memory but they do not have references as variables. Generally, both terms, constants, and literals are used interchangeably. For example, “const int =
4 min read
Escape Sequence in C
The escape sequence in C is the characters or the sequence of characters that can be used inside the string literal. The purpose of the escape sequence is to represent the characters that cannot be used normally using the keyboard. Some escape sequence characters are the part of ASCII charset but so
5 min read
bool in C
The bool in C is a fundamental data type in most that can hold one of two values: true or false. It is used to represent logical values and is commonly used in programming to control the flow of execution in decision-making statements such as if-else statements, while loops, and for loops. In this a
6 min read
Integer Promotions in C
Some data types like char , short int take less number of bytes than int, these data types are automatically promoted to int or unsigned int when an operation is performed on them. This is called integer promotion. For example no arithmetic calculation happens on smaller types like char, short and e
2 min read
Character Arithmetic in C
As already known character range is between -128 to 127 or 0 to 255. This point has to be kept in mind while doing character arithmetic. What is Character Arithmetic?Character arithmetic is used to implement arithmetic operations like addition, subtraction, multiplication, and division on characters
2 min read
Type Conversion in C
Type conversion in C is the process of converting one data type to another. The type conversion is only performed to those data types where conversion is possible. Type conversion is performed by a compiler. In type conversion, the destination data type can't be smaller than the source data type. Ty
4 min read
C Input/Output
Basic Input and Output in C
C language has standard libraries that allow input and output in a program. The stdio.h or standard input output library in C that has methods for input and output. scanf()The scanf() method, in C, reads the value from the console as per the type specified and store it in the given address. Syntax:
3 min read
Format Specifiers in C
The format specifier in C is used to tell the compiler about the type of data to be printed or scanned in input and output operations. They always start with a % symbol and are used in the formatted string in functions like printf(), scanf, sprintf(), etc. The C language provides a number of format
6 min read
printf in C
In C language, printf() function is used to print formatted output to the standard output stdout (which is generally the console screen). The printf function is a part of the C standard library <stdio.h> and it can allow formatting the output in numerous ways. Syntax of printfprintf ( "formatt
5 min read
scanf in C
In C programming language, scanf is a function that stands for Scan Formatted String. It is used to read data from stdin (standard input stream i.e. usually keyboard) and then writes the result into the given arguments. It accepts character, string, and numeric data from the user using standard inpu
2 min read
Scansets in C
scanf family functions support scanset specifiers which are represented by %[]. Inside scanset, we can specify single character or range of characters. While processing scanset, scanf will process only those characters which are part of scanset. We can define scanset by putting characters inside squ
2 min read
Formatted and Unformatted Input/Output functions in C with Examples
This article focuses on discussing the following topics in detail- Formatted I/O Functions.Unformatted I/O Functions.Formatted I/O Functions vs Unformatted I/O Functions.Formatted I/O Functions Formatted I/O functions are used to take various inputs from the user and display multiple outputs to the
9 min read
C Operators
Operators in C
In C language, operators are symbols that represent operations to be performed on one or more operands. They are the basic components of the C programming. In this article, we will learn about all the built-in operators in C with examples. What is a C Operator?An operator in C can be defined as the
14 min read
Arithmetic Operators in C
Arithmetic Operators are the type of operators in C that are used to perform mathematical operations in a C program. They can be used in programs to define expressions and mathematical formulas. What are C Arithmetic Operators?The C arithmetic operators are the symbols that are used to perform mathe
7 min read
Unary operators in C
Unary operators are the operators that perform operations on a single operand to produce a new value. Types of unary operatorsTypes of unary operators are mentioned below: Unary minus ( - )Increment ( ++ )Decrement ( -- )NOT ( ! )Addressof operator ( & )sizeof()1. Unary MinusThe minus operator (
4 min read
Relational Operators in C
In C, relational operators are the symbols that are used for comparison between two values to understand the type of relationship a pair of numbers shares. The result that we get after the relational operation is a boolean value, that tells whether the comparison is true or false. Relational operato
4 min read
Bitwise Operators in C
In C, the following 6 operators are bitwise operators (also known as bit operators as they work at the bit-level). They are used to perform bitwise operations in C. The & (bitwise AND) in C takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if bot
7 min read
C Logical Operators
Logical operators in C are used to combine multiple conditions/constraints. Logical Operators returns either 0 or 1, it depends on whether the expression result is true or false. In C programming for decision-making, we use logical operators. We have 3 logical operators in the C language: Logical AN
6 min read
Assignment Operators in C
Assignment operators are used for assigning value to a variable. The left side operand of the assignment operator is a variable and right side operand of the assignment operator is a value. The value on the right side must be of the same data-type of the variable on the left side otherwise the compi
3 min read
Increment and Decrement Operators in C
The increment ( ++ ) and decrement ( -- ) operators in C are unary operators for incrementing and decrementing the numeric values by 1 respectively. The incrementation and decrementation are one of the most frequently used operations in programming for looping, array traversal, pointer arithmetic, a
4 min read
Conditional or Ternary Operator (?:) in C
The conditional operator in C is kind of similar to the if-else statement as it follows the same algorithm as of if-else statement but the conditional operator takes less space and helps to write the if-else statements in the shortest way possible. It is also known as the ternary operator in C as it
3 min read
sizeof operator in C
Sizeof is a much-used operator in the C. It is a compile-time unary operator which can be used to compute the size of its operand. The result of sizeof is of the unsigned integral type which is usually denoted by size_t. sizeof can be applied to any data type, including primitive types such as integ
3 min read
Operator Precedence and Associativity in C
Operator precedence and associativity are rules that decide the order in which parts of an expression are calculated. Precedence tells us which operators should be evaluated first, while associativity determines the direction (left to right or right to left) in which operators with the same preceden
8 min read
C Control Statements Decision-Making
Decision Making in C (if , if..else, Nested if, if-else-if )
The conditional statements (also known as decision control structures) such as if, if else, switch, etc. are used for decision-making purposes in C programs. They are also known as Decision-Making Statements and are used to evaluate one or more conditions and make the decision whether to execute a s
11 min read
C - if Statement
The if in C is the simplest decision-making statement. It consists of the test condition and a block of code that is executed if and only if the given condition is true. Otherwise, it is skipped from execution. Let's take a look at an example: [GFGTABS] C #include <stdio.h> int main() { int n
4 min read
C if else Statement
The if else in C is an extension of the if statement which not only allows the program to execute one block of code if a condition is true, but also a different block if the condition is false. This enables making decisions with two possible outcomes. Let's take a look at an example: [GFGTABS] C #in
3 min read
C if else if ladder
In C, if else if ladder is an extension of if else statement used to test a series of conditions sequentially, executing the code for the first true condition. A condition is checked only if all previous ones are false. Once a condition is true, its code block executes, and the ladder ends. Example:
3 min read
Switch Statement in C
In C, switch statement is a control flow structure that allows you to execute one of many code blocks based on the value of an expression. It is often used in place of if-else ladder when there are multiple conditional codes. Example: [GFGTABS] C #include <stdio.h> int main() { // Switch varia
6 min read
Using Range in switch Case in C
You all are familiar with switch case in C, but did you know you can use a range of numbers instead of a single number or character in the case statement? Range in switch case can be useful when we want to run the same set of statements for a range of numbers so that we do not have to write cases se
2 min read
C - Loops
Loops in programming are used to repeat a block of code until the specified condition is met. A loop statement allows programmers to execute a statement or group of statements multiple times without repetition of code. [GFGTABS] C // C program to illustrate need of loops #include <stdio.h> int
6 min read
C for Loop
In C programming, the for loop is used to repeatedly execute a block of code as many times as instructed. It uses a variable (loop variable) whose value is used to decide the number of repetitions. It is generally used when we know how many times we want to repeat the code. Let's take a look at an e
4 min read
while Loop in C
The while loop in C allows a block of code to be executed repeatedly as long as a given condition remains true. It is often used when we want to repeat a block of code till some condition is satisfied. Let's take a look at an example: [GFGTABS] C #include <stdio.h> int main() { int i = 1; // C
5 min read
do...while Loop in C
The do...while loop is a type of loop in C that executes a block of code until the given condition is satisfied. The feature of do while loops is that unlike the while loop, which checks the condition before executing the loop, the do...while loop ensures that the code inside the loop is executed at
4 min read
For vs. While
In C, oops are the fundamental part of language that are used to repeat a block of code multiple times. The two most commonly used loops are the for loop and the while loop. Although they achieve the same result, their structure, use cases, and flexibility differ. The below table highlights some pri
4 min read
Continue Statement in C
The continue statement in C is a jump statement used to skip the current iteration of a loop and continue with the next iteration. It is used inside loops (for, while, or do-while) along with the conditional statements to bypass the remaining statements in the current iteration and move on to next i
4 min read
Break Statement in C
The break statement is one of the four jump statements in the C language. The purpose of the break statement in C is for unconditional exit from the loop What is break in C?The break in C is a loop control statement that breaks out of the loop when encountered. It can be used inside loops or switch
6 min read
goto Statement in C
The goto statement in C allows the program to jump to some part of the code, giving you more control over its execution. While it can be useful in certain situations, like error handling or exiting complex loops, it's generally not recommended because it can make the code harder to read and maintain
4 min read
C Functions
C Functions
A function in C is a set of statements that when called perform some specific tasks. It is the basic building block of a C program that provides modularity and code reusability. The programming statements of a function are enclosed within { } braces, having certain meanings and performing certain op
10 min read
User-Defined Function in C
A user-defined function is a type of function in C language that is defined by the user himself to perform some specific task. It provides code reusability and modularity to our program. User-defined functions are different from built-in functions as their working is specified by the user and no hea
6 min read
Parameter Passing Techniques in C
In C, there are different ways in which parameter data can be passed into and out of methods and functions. Let us assume that a function B() is called from another function A(). In this case, A is called the "caller function" and B is called the "called function or callee function". Also, the argum
5 min read
Function Prototype in C
In C, a function prototype is a statement that tells the compiler about the function’s name, its return type, numbers, and data types of its parameters. Using this information, the compiler cross-checks function parameters and their data type with function definition and function call. For example,
6 min read
How can I return multiple values from a function?
In C programming, a function can return only one value directly. However, C also provides several indirect methods in to return multiple values from a function. In this article, we will learn the different ways to return multiple values from a function in C. The most straightforward method to return
3 min read
main Function in C
The main function is an integral part of the programming languages such as C, C++, and Java. The main function in C is the entry point of a program where the execution of a program starts. It is a user-defined function that is mandatory for the execution of a program because when a C program is exec
4 min read
Implicit Return Type int in C
In C, every function has a return type that indicates the type of value it will return, and it is defined at the time of function declaration or definition. But in C language, it is possible to define functions without mentioning the return type and by default, int is implicitly assumed that the ret
2 min read
Callbacks in C
A callback is any executable code that is passed as an argument to another code, which is expected to call back (execute) the argument at a given time. In simple terms, a callback is the process of passing a function (executable code) to anther function as argument and then it is called by the passe
4 min read
Nested functions in C
Some programmer thinks that defining a function inside an another function is known as "nested function". But the reality is that it is not a nested function, it is treated as lexical scoping. Lexical scoping is not valid in C because the compiler cant reach/find the correct memory location of the i
2 min read
Variadic Functions in C
In C, variadic functions are functions that can take a variable number of arguments. This feature is useful when the number of arguments for a function is unknown. It takes one fixed argument and then any number of arguments can be passed. Let's take a look at an example: [GFGTABS] C #include <st
5 min read
_Noreturn function specifier in C
In C, the _Noreturn specifier is used to indicate that a function does not return a value. It tells the compiler that the function will either exit the program or enter an infinite loop, so it will never return control to the calling function. This helps the compiler to optimize code and issue warni
2 min read
Predefined Identifier __func__ in C
Before we start discussing __func__, let us write some code snippets and anticipate the output: C/C++ Code // C program to demonstrate working of a // Predefined Identifier __func__ #include <stdio.h> int main() { // %s indicates that the program will read strings printf("%s", __func
2 min read
C Library math.h Functions
The math.h header defines various C mathematical functions and one macro. All the functions available in this library take double as an argument and return double as the result. Let us discuss some important C math functions one by one. C Math Functions1. double ceil (double x) The C library functio
6 min read
C Arrays & Strings
C Arrays
Array in C is one of the most used data structures in C programming. It is a simple and fast way of storing multiple values under a single name. In this article, we will study the different aspects of array in C language such as array declaration, definition, initialization, types of arrays, array s
15+ min read
Properties of Array in C
An array in C is a fixed-size homogeneous collection of elements stored at a contiguous memory location. It is a derived data type in C that can store elements of different data types such as int, char, struct, etc. It is one of the most popular data types widely used by programmers to solve differe
8 min read
Multidimensional Arrays in C - 2D and 3D Arrays
Prerequisite: Arrays in C A multi-dimensional array can be defined as an array that has more than one dimension. Having more than one dimension means that it can grow in multiple directions. Some popular multidimensional arrays are 2D arrays and 3D arrays. In this article, we will learn about multid
10 min read
Initialization of Multidimensional Array in C
In C, multidimensional arrays are the arrays that contain more than one dimensions. These arrays are useful when we need to store data in a table or matrix-like structure. In this article, we will learn the different methods to initialize a multidimensional array in C. The easiest method for initial
4 min read
Pass Array to Functions in C
Passing an array to a function allows the function to directly access and modify the original array. In this article, we will learn how to pass arrays to functions in C. In C, arrays are always passed to function as pointers. They cannot be passed by value because of the array decay due to which, wh
3 min read
How to pass a 2D array as a parameter in C?
This post is an extension of How to dynamically allocate a 2D array in C? A one dimensional array can be easily passed as a pointer, but syntax for passing a 2D array to a function can be difficult to remember. One important thing for passing multidimensional arrays is, first array dimension does no
4 min read
What are the data types for which it is not possible to create an array?
In C, an array is a collection of variables of the same data type, stored in contiguous memory locations. Arrays can store data of primitive types like integers, characters, and floats, as well as user-defined types like structures. However, there are certain data types for which arrays cannot be di
2 min read
How to pass an array by value in C ?
In C programming, arrays are always passed as pointers to the function. There are no direct ways to pass the array by value. However, there is trick that allows you to simulate the passing of array by value by enclosing it inside a structure and then passing that structure by value. This will also p
2 min read
Strings in C
A String in C programming is a sequence of characters terminated with a null character '\0'. The C String is stored as an array of characters. The difference between a character array and a C string is that the string in C is terminated with a unique character '\0'. C String Declaration SyntaxDeclar
8 min read
Array of Strings in C
In C, an array of strings is a 2D array where each row contains a sequence of characters terminated by a '\0' NULL character (strings). It is used to store multiple strings in a single array. Let's take a look at an example: [GFGTABS] C #include <stdio.h> int main() { // Creating array of stri
3 min read
What is the difference between single quoted and double quoted declaration of char array?
In C programming, the way we declare and initialize a char array can differ based on whether we want to use a sequence of characters and strings. They are basically same with difference only of a '\0' NULL character. Double quotes automatically include the null terminator, making the array a string
2 min read
C String Functions
The C string functions are built-in functions that can be used for various operations and manipulations on strings. These string functions can be used to perform tasks such as string copy, concatenation, comparison, length, etc. The <string.h> header file contains these string functions. In th
8 min read
C Pointers
C Pointers
A pointer is a variable that stores the memory address of another variable. Instead of holding a direct value, it holds the address where the value is stored in memory. There are 2 important operators that we will use in pointers concepts i.e. Dereferencing operator(*) used to declare pointer variab
10 min read
Pointer Arithmetics in C with Examples
Pointer Arithmetic is the set of valid arithmetic operations that can be performed on pointers. The pointer variables store the memory address of another variable. It doesn't store any value. Hence, there are only a few operations that are allowed to perform on Pointers in C language. The C pointer
10 min read
C - Pointer to Pointer (Double Pointer)
In C, double pointers are those pointers which stores the address of another pointer. The first pointer is used to store the address of the variable, and the second pointer is used to store the address of the first pointer. That is why they are also known as a pointer to pointer. Let's take a look a
5 min read
Function Pointer in C
In C, a function pointer is a type of pointer that stores the address of a function, allowing functions to be passed as arguments and invoked dynamically. It is useful in techniques such as callback functions, event-driven programs, and polymorphism (a concept where a function or operator behaves di
6 min read
How to Declare a Pointer to a Function?
A pointer to a function is similar to a pointer to a variable. However, instead of pointing to a variable, it points to the address of a function. This allows the function to be called indirectly, which is useful in situations like callback functions or event-driven programming. In this article, we
2 min read
Pointer to an Array | Array Pointer
A pointer to an array is a pointer that points to the whole array instead of the first element of the array. It considers the whole array as a single unit instead of it being a collection of given elements. Consider the following example: [GFGTABS] C #include<stdio.h> int main() { int arr[5] =
5 min read
Difference between constant pointer, pointers to constant, and constant pointers to constants
In this article, we will discuss the differences between constant pointer, pointers to constant & constant pointers to constants. Pointers are the variables that hold the address of some other variables, constants, or functions. There are several ways to qualify pointers using const. Pointers to
3 min read
Pointer vs Array in C
Most of the time, pointer and array accesses can be treated as acting the same, the major exceptions being: 1. the sizeof operator sizeof(array) returns the amount of memory used by all elements in the array sizeof(pointer) only returns the amount of memory used by the pointer variable itself 2. the
1 min read
Dangling, Void , Null and Wild Pointers in C
In C programming pointers are used to manipulate memory addresses, to store the address of some variable or memory location. But certain situations and characteristics related to pointers become challenging in terms of memory safety and program behavior these include Dangling (when pointing to deall
6 min read
Near, Far and Huge Pointers in C
In older times, the intel processors had 16-bit registers, but the address bus was 20-bits wide. Due to this, CPU registers were not able to hold the entire address at once. As a solution, the memory was divided into segments of 64 kB size, and the near pointers, far pointers, and huge pointers were
4 min read
restrict Keyword in C
The restrict keyword is a type qualifier that was introduced in the C99 standard. It is used to tell the compiler that a pointer is the only reference or access point to the memory it points to, allowing the compiler to make optimizations based on that information. Let's take a look at an example: [
3 min read
C User-Defined Data Types
C Structures
The structure in C is a user-defined data type that can be used to group items of possibly different types into a single type. The struct keyword is used to define the structure in the C programming language. The items in the structure are called its member and they can be of any valid data type. Ad
10 min read
dot (.) Operator in C
In C, the dot (.) operator is used to access members of user defined data types such as a structure or union. Also known as the direct member access operator, it allows us to access the data of the struct and union via the name of variables. Let's take a look at an example: [GFGTABS] C #include <
2 min read
C typedef
The typedef is a keyword that is used to provide existing data types with a new name. The C typedef keyword is used to redefine the name of already existing data types. When names of datatypes become difficult to use in programs, typedef is used with user-defined datatypes, which behave similarly to
4 min read
Structure Member Alignment, Padding and Data Packing
In C, the structures are used as data packs. They don't provide any data encapsulation or data hiding features. In this article, we will discuss the property of structure padding in C along with data alignment and structure packing. Data Alignment in MemoryEvery data type in C will have alignment re
12 min read
Flexible Array Members in a structure in C
Flexible Array Member(FAM) is a feature introduced in the C99 standard of the C programming language. For the structures in C programming language from C99 standard onwards, we can declare an array without a dimension and whose size is flexible in nature.Such an array inside the structure should pre
4 min read
C Unions
In C, union is a user-defined data type that can contain elements of the different data types just like structure. But unlike structures, all the members in the C union are stored in the same memory location. Due to this, only one member can store data at the given point in time. Let's take a look a
6 min read
Bit Fields in C
In C, we can specify the size (in bits) of the structure and union members. The idea of bit-field is to use memory efficiently when we know that the value of a field or group of fields will never exceed a limit or is within a small range. C Bit fields are used when the storage of our program is limi
8 min read
Difference Between Structure and Union in C
In C programming, both structures and unions are used to group different types of data under a single name, but they behave in different ways. The main difference lies in how they store data. The below table lists the primary differences between the C structures and unions: Parameter Structure Union
4 min read
Anonymous Union and Structure in C
In C, anonymous unions and anonymous structures are the unnamed structures and unions whose members can be directly accessed without creating a variable. These are generally used when the members of the union or structure need to be accessed directly, without using a separate name for the union or s
3 min read
Enumeration (or enum) in C
Enumeration (or enum) is a user defined data type in C. It is mainly used to assign names to integral constants, the names make a program easy to read and maintain. enum State {Working = 1, Failed = 0}; The keyword 'enum' is used to declare new enumeration types in C and C++. Enums in C allow you to
4 min read
C Storage Classes
Storage Classes in C
C Storage Classes are used to describe the features of a variable/function. These features basically include the scope, visibility, and lifetime which help us to trace the existence of a particular variable during the runtime of a program. C language uses 4 storage classes, namely: Storage classes i
6 min read
extern Keyword in C
extern keyword in C applies to C variables (data objects) and C functions. Basically, the extern keyword extends the visibility of the C variables and C functions. That's probably the reason why it was named extern. Though most people probably understand the difference between the "declaration" and
7 min read
Static Variables in C
Static variables have the property of preserving their value even after they are out of their scope! Hence, a static variable preserves its previous value in its previous scope and is not initialized again in the new scope. Syntax: static data_type var_name = var_value;Static variables in C retain t
4 min read
Initialization of Static Variables in C
In C, a static variable are those variables whose lifetime is till the end of the program. It means that once it is initialized, it will live in the program till it ends. It can retain its value between function calls, unlike regular local variables that are reinitialized each time the function is c
2 min read
Static Functions in C
In C, functions are global by default. The static keyword before a function name makes it a static function. For example, the below function fun() is static. [GFGTABS] C #include <stdio.h> static int fun(void) { printf("I am a static function "); } int main() { fun(); return 0; } [/G
3 min read
Understanding "volatile" qualifier in C | Set 2 (Examples)
The volatile keyword is intended to prevent the compiler from applying any optimizations on objects that can change in ways that cannot be determined by the compiler. Objects declared as volatile are omitted from optimization because their values can be changed by code outside the scope of current c
5 min read
Understanding "register" keyword in C
Registers are faster than memory to access, so the variables which are most frequently used in a C program can be put in registers using the register keyword. The keyword register hints to the compiler that a given variable can be put in a register. It's the compiler's choice to put it in a register
3 min read
C Memory Management
Memory Layout of C Programs
A typical memory representation of a C program consists of the following sections. Text segment (i.e. instructions)Initialized data segment Uninitialized data segment (bss)Heap Stack A typical memory layout of a running process 1. Text Segment: A text segment, also known as a code segment or simply
6 min read
Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()
Since C is a structured language, it has some fixed rules for programming. One of them includes changing the size of an array. An array is a collection of items stored at contiguous memory locations. As can be seen, the length (size) of the array above is 9. But what if there is a requirement to cha
9 min read
Difference Between malloc() and calloc() with Examples
The functions malloc() and calloc() are library functions that allocate memory dynamically. Dynamic means the memory is allocated during runtime (execution of the program) from the heap segment. Initializationmalloc() allocates a memory block of given size (in bytes) and returns a pointer to the beg
3 min read
What is Memory Leak? How can we avoid?
A memory leak occurs when programmers create a memory in a heap and forget to delete it. The consequence of the memory leak is that it reduces the performance of the computer by reducing the amount of available memory. Eventually, in the worst case, too much of the available memory may become alloca
3 min read
Dynamic Array in C
Array in C is static in nature, so its size should be known at compile time and we can't change the size of the array after its declaration. Due to this, we may encounter situations where our array doesn't have enough space left for required elements or we allotted more than the required memory lead
9 min read
How to dynamically allocate a 2D array in C?
Following are different ways to create a 2D array on the heap (or dynamically allocate a 2D array).In the following examples, we have considered 'r' as number of rows, 'c' as number of columns and we created a 2D array with r = 3, c = 4 and the following values 1 2 3 4 5 6 7 8 9 10 11 12 1) Using a
5 min read
Dynamically Growing Array in C
Prerequisite: Dynamic Memory Allocation in C A Dynamically Growing Array is a type of dynamic array, which can automatically grow in size to store data. The C language only has static arrays whose size should be known at compile time and cannot be changed after declaration. This leads to problems li
7 min read
C Preprocessor
C Preprocessors
Preprocessors are programs that process the source code before compilation. Several steps are involved between writing a program and executing a program in C. Let us have a look at these steps before we actually start learning about Preprocessors. You can see the intermediate steps in the above diag
10 min read
C Preprocessor Directives
In almost every C program we come across, we see a few lines at the top of the program preceded by a hash (#) sign. They are called preprocessor directives and are preprocessed by the preprocessor before actual compilation begins. The end of these lines is identified by the newline character '\n', n
8 min read
How a Preprocessor works in C?
Compiling a C program - Behind the Scene A Preprocessor is a system software (a computer program that is designed to run on computer's hardware and application programs). It performs preprocessing of the High Level Language(HLL). Preprocessing is the first step of the language processing system. Lan
3 min read
Header Files in C
In C language, header files contain a set of predefined standard library functions. The .h is the extension of the header files in C and we request to use a header file in our program by including it with the C preprocessing directive "#include". C Header files offer the features like library functi
7 min read
What’s difference between header files "stdio.h" and "stdlib.h" ?
In C programming, standard header files provide various inbuilt functionalities and two of the most commonly used standard header files are stdio.h and stdlib.h. The <stdio.h> provides Standard Input Output tools such as printf(), scanf(), etc while <stdlib.h> provides some commonly used
4 min read
How to write your own header file in C?
As we all know that files with .h extension are called header files in C. These header files generally contain function declarations which we can be used in our main C program, like for e.g. there is need to include stdio.h in our C program to use function printf() in the program. So the question ar
4 min read
Macros and its types in C
In C, a macro is a piece of code in a program that is replaced by the value of the macro. Macro is defined by #define directive. Whenever a macro name is encountered by the compiler, it replaces the name with the definition of the macro. Macro definitions need not be terminated by a semi-colon(;). E
6 min read
Interesting Facts about Macros and Preprocessors in C
In a C program, all lines that start with # are processed by preprocessor which is a special program invoked by the compiler. by this we mean to say that the ‘#’ symbol is used to process the functionality prior than other statements in the program, that is, which means it processes some code before
6 min read
# and ## Operators in C
In C, # and ## operators are preprocessor operators using in macros for token manipulation. They are known as stringizing and token pasting operators and are used in macro definition with #define preprocessor. In this article, we will learn about these operators and how to use them in C programs. St
3 min read
How to print a variable name in C?
Printing a variable name means printing the identifier that is assigned to the variable. To print it, it should be in the form of string. This can be done by using stringification. Stringification in C is the method to convert the argument of a function like macro to a string. This can be done with
1 min read
Multiline macros in C
In this article, we will discuss how to write a multi-line macro. We can write multi-line macro same like function, but each statement ends with "\". Let us see with example. Below is simple macro, which accepts input number from user, and prints whether entered number is even or odd. #include <s
3 min read
Variable length arguments for Macros
Like functions, we can also pass variable length arguments to macros. For this we will use the following preprocessor identifiers.To support variable length arguments in macro, we must include ellipses (...) in macro definition. There is also "__VA_ARGS__" preprocessing identifier which takes care o
2 min read
Branch prediction macros in GCC
One of the most used optimization techniques in the Linux kernel is " __builtin_expect". When working with conditional code (if-else statements), we often know which branch is true and which is not. If compiler knows this information in advance, it can generate most optimized code. Let us see macro
2 min read
Difference between typedef and #define in C
In C, both typedef and #define can be used to create aliases for existing types or values, but their behaviors and implementation differ significantly. typedef is a keyword used to create type aliases(nicknames) that are checked by the compiler, while #define is a preprocessor directive that perform
3 min read
Difference between #define and const in C
In C, both #define and const define constant values, but these constants differ greatly in their behaviors and implementation. #define is a preprocessor directive used to define constants that are replaced by their value during preprocessing, before actual compilation begins. while const defines a t
3 min read
C File Handling
Basics of File Handling in C
File handling in C is the process in which we create, open, read, write, and close operations on a file. C language provides different functions such as fopen(), fwrite(), fread(), fseek(), fprintf(), etc. to perform input, output, and many different C file operations in our program. Why do we need
15 min read
C fopen() Function
In C, the fopen() function is used to open a file in the specified mode. The function returns a file pointer (FILE *) which is used to perform further operations on the file, such as reading from or writing to it. If the file exists then the fopen() function opens the particular file else a new file
5 min read
EOF, getc() and feof() in C
In this article, we will discuss the EOF, getc() function and feof() function in C. What is EOF?In C, EOF is a constant macro defined in the <stdlib.h> header file that is used to denote the end of the file in C file handling. It is used by various file reading functions such as fread(), gets(
3 min read
fgets() and gets() in C language
For reading a string value with spaces, we can use either gets() or fgets() in C programming language. Here, we will see what is the difference between gets() and fgets(). fgets()The fgets() reads a line from the specified stream and stores it into the string pointed to by str. It stops when either
3 min read
fseek() vs rewind() in C
In C, the functions fseek() and rewind() helps in manipulating the position of the pointer in the opened file but serve different purposes and have distinct working. The below table lists the major differences between fseek() and rewind() in C: Featurefseek()rewind()FunctionalityMoves the file point
2 min read
What is return type of getchar(), fgetc() and getc() ?
In C, getchar(), fgetc(), and getc() all are the functions used for reading characters from input buffer. This buffer is standard input buffer for getchar() and can be any specified file for getc() and fgetc(). In this article, we will learn about the return type of these functions and why it matter
3 min read
Read/Write Structure From/to a File in C
For writing in the file, it is easy to write string or int to file using fprintf and putc, but you might have faced difficulty when writing contents of the struct. fwrite and fread make tasks easier when you want to write and read blocks of data. Writing Structure to a File using fwriteWe can use fw
3 min read
C Program to Print Contents of File
C language allows users to process the files in its programs. Reading a file is a step-by-step process in which we first have to prepare the file only after which we can start reading. In this article, we will learn how to read and print the contents of a file using C program. The simplest method to
4 min read
C Program to Delete a File
C language allows the manipulation of the files present in the accessible storage directory allowing programmers to create, read, write and delete files. In this article, we will learn how to delete a file using a C program. A file stored in the system can be deleted from a C program using the stand
2 min read
C Program to Merge Contents of Two Files into a Third File
Merging two files into a third file means copying the data of the two files and pasting them into the third file one after another. In this article, we will learn how to merge the contents of two files using a C program. The simplest method to merge two files into a third file is by first reading th
3 min read
What is the difference between printf, sprintf and fprintf?
The printf() function is used as a standard method for output operations and C also provides some different versions of this function such as sprintf() and fprintf(). These functions are also used for output operations but in different contexts. The below table lists the primary differences between
3 min read
Difference between getc(), getchar(), getch() and getche()
In C, getc(), getchar(), getch(), and getche() are all functions that is used to read input character in different contexts. Although these functions are used for similar purposes and have similar names, they have different behaviours and use cases. The below table lists the primary differences betw
3 min read
Top 50 C Coding Interview Questions and Answers (2025)
C is the most popular programming language developed by Dennis Ritchie at the Bell Laboratories in 1972 to develop the UNIX operating systems. It is a general-purpose and procedural programming language. It is faster than the languages like Java and Python. C is the most used language in top compani
15+ min read