0% found this document useful (0 votes)
22 views12 pages

C Definition

Variables are containers that store data values of different types like integers, floats, and characters. A variable is a named memory location that programs can manipulate. Variables have specific types that determine their size, value range, and operations. C supports basic variable types like int, float, char. Arrays allow storing multiple values of the same type in contiguous memory locations that can be accessed using indices. Pointers store the address of other variables and are useful for passing arguments by reference, accessing arrays, dynamic memory allocation, and implementing data structures.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
22 views12 pages

C Definition

Variables are containers that store data values of different types like integers, floats, and characters. A variable is a named memory location that programs can manipulate. Variables have specific types that determine their size, value range, and operations. C supports basic variable types like int, float, char. Arrays allow storing multiple values of the same type in contiguous memory locations that can be accessed using indices. Pointers store the address of other variables and are useful for passing arguments by reference, accessing arrays, dynamic memory allocation, and implementing data structures.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 12

Variables are containers for storing data values.

In C, there are different types of variables (defined with different keywords), for example:
 int - stores integers (whole numbers), without decimals, such as 123 or -123
 float - stores floating point numbers, with decimals, such as 19.99 or -19.99
 char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single quotes
A variable is nothing but a name given to a storage area that our programs can manipulate. Each variable
in C has a specific type, which determines the size and layout of the variable's memory; the range of
values that can be stored within that memory; and the set of operations that can be applied to the variable.

The name of a variable can be composed of letters, digits, and the underscore character. It must begin
with either a letter or an underscore. Upper and lowercase letters are distinct because C is case-sensitive.
Based on the basic types explained in the previous chapter, there will be the following basic variable
types −
A variable in simple terms is a storage place that has some memory allocated to it. Basically, a variable
is used to store some form of data. Different types of variables require different amounts of memory,
different type of memory locations, and some specific set of operations that can be applied to them.

Operators are used to perform operations on variables and values.


Operators are the foundation of any programming language. We can define operators as symbols that
help us to perform specific mathematical and logical computations on operands. In other words, we can
say that an operator operates the operands. For example, ‘+’ is an operator used for addition.

C Array
- An array is defined as the collection of similar type of data items stored at contiguous memory
locations. Arrays are the derived data type in C programming language which can store the primitive type
of data such as int, char, double, float, etc. It also has the capability to store the collection of derived data
types, such as pointers, structure, etc. The array is the simplest data structure where each data element can
be randomly accessed by using its index number.

- C array is beneficial if you have to store similar elements. For example, if we want to store the marks
of a student in 6 subjects, then we don't need to define different variables for the marks in the different
subject. Instead of that, we can define an array which can store the marks in each subject at the
contiguous memory locations.
- By using the array, we can access the elements easily. Only a few lines of code are required to access
the elements of the array.

Properties of Array
The array contains the following properties.
o Each element of an array is of same data type and carries the same size, i.e., int = 4 bytes.
o Elements of the array are stored at contiguous memory locations where the first element is stored
at the smallest memory location.
o Elements of the array can be randomly accessed since we can calculate the address of each element
of the array with the given base address and the size of the data element.

Advantage of C Array
1) Code Optimization: Less code to the access the data.
2) Ease of traversing: By using the for loop, we can retrieve the elements of an array easily.
3) Ease of sorting: To sort the elements of the array, we need a few lines of code only.
4) Random Access: We can access any element randomly using the array.
Disadvantage of C Array
1) Fixed Size: Whatever size, we define at the time of declaration of the array, we can't exceed the limit.
So, it doesn't grow the size dynamically like LinkedList which we will learn later.
Arrays a kind of data structure that can store a fixed-size sequential collection of elements of the same
type. An array is used to store a collection of data, but it is often more useful to think of an array as a
collection of variables of the same type.

- Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare
one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent
individual variables. A specific element in an array is accessed by an index.
All arrays consist of contiguous memory locations. The lowest address corresponds to the first element
and the highest address to the last element.

Advantage of Arrays in C
 Less amount of code : Using array we can aggregate N variables of same data type in a single data
structure. Otherwise we have to declare N individual variables.
 Easy access of elements : We can access any element of array using array name and index. We can
access all elements serially by iterating from index 0 to size-1 using a loop.
 Easy to implement algorithms : Certain algorithms can be easily implemented using array like
searching and sorting, finding maximum and minimum elements.
 Random Access : We can access any elements of array in O(1) time complexity.

Disadvantages or Limitations of Arrays in C


 Array is Static Data Structure. We cannot change the size of array in run-time.
 We must know in advance that how many elements are to be stored in array.
 Only elements of same data types can be stored in an array. We cannot store elements of multiple data
types in a single array.
 As Array elements are stored in consecutive memory locations. So, insertions and deletions of an
element is time consuming as we have to shift other elements one position ahead or back respectively.
 C doesn't perform any array index bound checking. In and array of size N, you can write code to access
N+5th element without getting error. When we try to access elements from outside of array boundaries,
we will get garbage value.
 As we cannot change the size of an array, developers generally declares large arrays to handle any
future data expansion. This ends up in creating large arrays, where most of the space is unused.

Array
1. It is a group of variables of similar data types referred to by a single element.
2. Its elements are stored in a contiguous memory location.
3. The size of the array should be mentioned while declaring it.
4. Array elements are always counted from zero (0) onward.
5. Array elements can be accessed using the position of the element in the array.
6. The array can have one or more dimensions.

- An array in C/C++ or be it in any programming language is a collection of similar data items stored
at contiguous memory locations and elements can be accessed randomly using indices of an array.
They can be used to store the collection of primitive data types such as int, float, double, char, etc of
any particular type. To add to it, an array in C/C++ can store derived data types such as structures,
pointers etc. Given below is the picture representation of an array.
C Pointers
- The pointer in C language is a variable which stores the address of another variable. This variable can
be of type int, char, array, function, or any other pointer. The size of the pointer depends on the
architecture. However, in 32-bit architecture the size of a pointer is 2 byte.
- Some C programming tasks are performed more easily with pointers, and other tasks, such as dynamic
memory allocation, cannot be performed without using pointers. So it becomes necessary to learn pointers
to become a perfect C programmer. Let's start learning them in simple and easy steps.
As you know, every variable is a memory location and every memory location has its address defined
which can be accessed using ampersand (&) operator, which denotes an address in memory. Consider the
following example, which prints the address of the variables defined –

Uses of Pointers in C
The C pointer is a very powerful tool that is widely used in C programming to perform various useful
operations. It is used to achieve the following functionalities in C:
1. Pass Arguments by Reference
2. Accessing Array Elements
4. Return Multiple Values from Function
5. Dynamic Memory Allocation
5. Implementing Data Structures
6. In System-Level Programming where memory addresses are useful.
7. In locating the exact value at some memory location.
8. To avoid compiler confusion for the same variable name.
9. To use in Control Tables.

Advantage of pointer
1) Pointer reduces the code and improves the performance, it is used to retrieving strings, trees, etc.
and used with arrays, structures, and functions.
2) We can return multiple values from a function using the pointer.
3) It makes you able to access any memory location in the computer's memory.

Usage of pointer
There are many applications of pointers in c language.
1) Dynamic memory allocation
In c language, we can dynamically allocate memory using malloc() and calloc() functions where the
pointer is used.
2) Arrays, Functions, and Structures
Pointers in c language are widely used in arrays, functions, and structures. It reduces the code and
improves the performance.
NULL Pointer
A pointer that is not assigned any value but NULL is known as the NULL pointer. If you don't have any
address to be specified in the pointer at the time of declaration, you can assign NULL value. It will
provide a better approach.

Arrays allow to define type of variables that can hold several data items of the same kind.
Similarly structure is another user defined data type available in C that allows to combine data items of
different kinds.

Pointers to Structures
You can define pointers to structures in the same way as you define pointer to any other variable −

Dynamic arrays are very useful data structures. They can be initialized with variable size at runtime. This
size can be modified later in the program to expand (or) shrink the array. Unlike fixed-size arrays and
Variable Length Arrays, Dynamically sized arrays are allocated in the heap. Flexible Array Members
closely resemble dynamic sized arrays. They're used in structs and provide a data member which has
similar properties as dynamic sized arrays.

Pointer to Array vs Array of Pointers

*Pointer to an array: Pointer to an array is also known as array pointer. We are using the pointer to
access the components of the array.
int a[3] = {3, 4, 5 };
int *ptr = a;
We have a pointer ptr that focuses to the 0th component of the array. We can likewise declare a pointer
that can point to whole array rather than just a single component of the array. Syntax:
data type (*var name)[size of array];
Declaration of the pointer to an array:
// pointer to an array of five numbers
int (* ptr)[5] = NULL;
*Array of pointers: “Array of pointers” is an array of the pointer variables. It is also known as pointer
arrays. Syntax:
int *var_name[array_size];
Declaration of an array of pointers:
int *ptr[3];
We can make separate pointer variables which can point to the different values or we can make one
integer array of pointers that can point to all the values.
Pointer to Function vs Function Pointer

Linked List
A Linked List is a linear data structure. Every linked list has two parts, the data section and the address
section that holds the address of the next element in the list, which is called a node.

The size of the linked list is not fixed, and data items can be added at any locations in the list. The
disadvantage is that to get to a node, we must traverse to all the way from the first node to the node that
we require. The Linked List is like an array but unlike an array, it is not stored sequentially in the
memory.

o Linked List can be defined as collection of objects called nodes that are randomly stored in the
memory.
o A node contains two fields i.e. data stored at that particular address and the pointer which contains
the address of the next node in the memory.
o The last node of the list contains pointer to the null.

Uses of Linked List

o The list is not required to be contiguously present in the memory. The node can reside any where
in the memory and linked together to make a list. This achieves optimized utilization of space.
o list size is limited to the memory size and doesn't need to be declared in advance.
o Empty node can not be present in the linked list.
o We can store values of primitive types or objects in the singly linked list.

Why use linked list over array?

Till now, we were using array data structure to organize the group of elements that are to be stored
individually in the memory. However, Array has several advantages and disadvantages which must be
known in order to decide the data structure which will be used throughout the program.

Array contains following limitations:


1. The size of array must be known in advance before using it in the program.
2. Increasing size of the array is a time taking process. It is almost impossible to expand the size of
the array at run time.
3. All the elements in the array need to be contiguously stored in the memory. Inserting any element
in the array needs shifting of all its predecessors.

Linked list is the data structure which can overcome all the limitations of an array. Using linked list is
useful because,
1. It allocates the memory dynamically. All the nodes of linked list are non-contiguously stored in the
memory and linked together with the help of pointers.
2. Sizing is no longer a problem since we do not need to define its size at the time of declaration. List
grows as per the program's demand and limited to the available memory space.

Advantages Of Linked List:


 Dynamic data structure: A linked list is a dynamic arrangement so it can grow and shrink at runtime
by allocating and deallocating memory. So there is no need to give the initial size of the linked list.
 No memory wastage: In the Linked list, efficient memory utilization can be achieved since the size of
the linked list increase or decrease at run time so there is no memory wastage and there is no need to
pre-allocate the memory.
 Implementation: Linear data structures like stacks and queues are often easily implemented using a
linked list.
 Insertion and Deletion Operations: Insertion and deletion operations are quite easier in the linked list.
There is no need to shift elements after the insertion or deletion of an element only the address present
in the next pointer needs to be updated.
Disadvantages Of Linked List:
 Memory usage: More memory is required in the linked list as compared to an array. Because in a
linked list, a pointer is also required to store the address of the next element and it requires extra
memory for itself.
 Traversal: In a Linked list traversal is more time-consuming as compared to an array. Direct access to
an element is not possible in a linked list as in an array by index. For example, for accessing a node at
position n, one has to traverse all the nodes before it.
 Reverse Traversing: In a singly linked list reverse traversing is not possible, but in the case of
a doubly-linked list, it can be possible as it contains a pointer to the previously connected nodes with
each node. For performing this extra memory is required for the back pointer hence, there is a wastage
of memory.
 Random Access: Random access is not possible in a linked list due to its dynamic memory allocation.

Struct
Arrays allow to define type of variables that can hold several data items of the same kind.
Similarly structure is another user defined data type available in C that allows to combine data items of
different kinds.
What is a structure?
A structure is a key word that create user defined data type in C/C++. A structure creates a data type that
can be used to group items of possibly different types into a single type.

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(;).

C Macros
A macro is a segment of code which is replaced by the value of macro. Macro is defined by #define
directive. There are two types of macros:
1. Object-like Macros
2. Function-like Macros
Object-like Macros
The object-like macro is an identifier that is replaced by value. It is widely used to represent numeric
constants. For example:
1. #define PI 3.14
Here, PI is the macro name which will be replaced by the value 3.14.

Function-like Macros
The function-like macro looks like function call. For example:
1. #define MIN(a,b) ((a)<(b)?(a):(b))
Here, MIN is the macro name.
Visit #define to see the full example of object-like and function-like macros.

Object like Macros in C


An object like macros in C programming is simply the macros that get replaced by certain values or
segments of code.
In the above example, in the introduction, we saw the macro with the name PI and value 3.14 it is an
example of an object like macros.
We can define macros with different datatypes as shown as follows but we can't use the same macro
names for 2 different values -

Function Like Macros in C


In the function like macros are very similar to the actual function in C programming.
We can pass the arguments with the macro name and perform the actions in the code segment.
In macros there is no type checking of arguments so we can use it as an advantage to pass different
datatypes in same macros in C language.

Conclusion

 Macro is a piece of code or value that is get replaced with the macro name before the execution of the
program.
 Preprocessor performs different actions on preprocessor directives and for the macro definition, we
use the #define preprocessor directive.
 The work of #define is that it replaces the macro body with the macro value at the time of
preprocessing.
 It is a good idea to use the macros in code as per the requirement and utilize the different types of
macros.
 Predefined macros can do so many things which aren't possible with normal C programming.

Difference between Inline and Macro in C++ :


S.N
O Inline Macro

An inline function is defined by Whereas the macros are defined by


1. the inline keyword. the #define keyword.

Through inline function, the class’s Whereas macro can’t access the class’s data
2. data members can be accessed. members.

In the case of inline function, the Whereas in the case of macros, the program
3. program can be easily debugged. can’t be easily debugged.

Whereas in the case of macro, the


In the case of inline, the arguments arguments are evaluated every time
4. are evaluated only once. whenever macro is used in the program.

In C++, inline may be defined either Whereas the macro is all the time defined at
5. inside the class or outside the class. the beginning of the program.

In C++, inside the class, the short


length functions are automatically
6. made the inline functions. While the macro is specifically defined.

7. Inline is not as widely used as macros. While the macro is widely used.

Inline is not used in competitive While the macro is very much used in
8. programming. competitive programming.

Inline function is terminated by the While the macro is not terminated by any
9. curly brace at the end. symbol, it is terminated by a new line.
- The inline function can be substituted at the place where the function call is happening. Function
substitution is always compiler choice.
 In an inline function, a function call is replaced by the actual program code.
 Most of the Inline functions are used for small computations. They are not suitable for large
computing.
 An inline function is similar to a normal function. The only difference is that we place a keyword
inline before the function name.

1. Inline :
An inline function is a normal function that is defined by the inline keyword. An inline function is a short
function that is expanded by the compiler. And its arguments are evaluated only once. An inline functions
are the short length functions that are automatically made the inline functions without using
the inline keyword inside the class.
Syntax of an Inline function:
inline return_type function_name ( parameters ){
// inline function code
}
2. Macro :
It is also called preprocessors directive. The macros are defined by the #define keyword. Before the
program compilation, the preprocessor examines the program whenever the preprocessor detects the
macros then preprocessor replaces the macro by the macro definition.
Syntax of Macro:
#define MACRO_NAME Macro_definition
C Memory Layout
- A typical memory representation of a C program consists of the following sections.
1. Text segment (i.e. instructions)
2. Initialized data segment
3. Uninitialized data segment (bss)
4. Heap
5. Stack

C Memory Layout
Memory layout của của một chương trình C/C++ gồm 5 phần chính: Text Segment, Initialized Data
Segment, Uninitialized Data Segment, Heap và Stack

2.1 Text Segment


Text Segment ở vùng nhớ của địa chỉ thấp nhất, đây là phần chứa các đoạn mã lệnh của chương trình.

2.2 Initialized Data Segment (DS)


Initialized Data Segment ( Data Segment ) là nơi lưu trữ global variables, static variables với điều kiện
các biến này được khởi tạo bởi programmer với giá trị khác 0.
int global = 100;
int foo() {
static int number = 10;
return 0;
}
Trong đoạn chương chính trên, biến global được khởi tạo với giá trị 100, và biến static number được khởi
với giá trị 10 bởi programmer nên được lưu trữ vào Initialized Data Segment.

2.3 Uninitialized Data Segment (BSS)


Uninitialized Data Segment (BSS) là nơi lưu trữ global variables, static variables không được khởi
tạo hoặc khởi tạo với giá trị bằng 0.
int global;
int foo() {
static int number = 0;
return 0;
}

1. Text Segment: A text segment, also known as a code segment or simply as text, is one of the sections of
a program in an object file or in memory, which contains executable instructions.
As a memory region, a text segment may be placed below the heap or stack in order to prevent heaps and
stack overflows from overwriting it.
Usually, the text segment is sharable so that only a single copy needs to be in memory for frequently
executed programs, such as text editors, the C compiler, the shells, and so on. Also, the text segment is
often read-only, to prevent a program from accidentally modifying its instructions.
2. Initialized Data Segment: Initialized data segment, usually called simply the Data Segment. A data
segment is a portion of the virtual address space of a program, which contains the global variables and
static variables that are initialized by the programmer.
Note that, the data segment is not read-only, since the values of the variables can be altered at run time.
This segment can be further classified into the initialized read-only area and the initialized read-write
area.
For instance, the global string defined by char s[] = “hello world” in C and a C statement like int debug=1
outside the main (i.e. global) would be stored in the initialized read-write area. And a global C statement
like const char* string = “hello world” makes the string literal “hello world” to be stored in the initialized
read-only area and the character pointer variable string in the initialized read-write area.
Ex: static int i = 10 will be stored in the data segment and global int i = 10 will also be stored in data
segment

3. Uninitialized Data Segment: Uninitialized data segment often called the “bss” segment, named after an
ancient assembler operator that stood for “block started by symbol.” Data in this segment is initialized by
the kernel to arithmetic 0 before the program starts executing uninitialized data starts at the end of the
data segment and contains all global variables and static variables that are initialized to zero or do not
have explicit initialization in source code.
For instance, a variable declared static int i; would be contained in the BSS segment.
For instance, a global variable declared int j; would be contained in the BSS segment.

4. Stack: The stack area traditionally adjoined the heap area and grew in the opposite direction; when the
stack pointer met the heap pointer, free memory was exhausted. (With modern large address spaces and
virtual memory techniques they may be placed almost anywhere, but they still typically grow in opposite
directions.)
The stack area contains the program stack, a LIFO structure, typically located in the higher parts of
memory. On the standard PC x86 computer architecture, it grows toward address zero; on some other
architectures, it grows in the opposite direction. A “stack pointer” register tracks the top of the stack; it is
adjusted each time a value is “pushed” onto the stack. The set of values pushed for one function call is
termed a “stack frame”; A stack frame consists at minimum of a return address.
Stack, where automatic variables are stored, along with information that is saved each time a function is
called. Each time a function is called, the address of where to return to and certain information about the
caller’s environment, such as some of the machine registers, are saved on the stack. The newly called
function then allocates room on the stack for its automatic variables. This is how recursive functions in C
can work. Each time a recursive function calls itself, a new stack frame is used, so one set of variables
doesn’t interfere with the variables from another instance of the function.
5. Heap: Heap is the segment where dynamic memory allocation usually takes place.
The heap area begins at the end of the BSS segment and grows to larger addresses from there. The Heap
area is managed by malloc, realloc, and free, which may use the brk and sbrk system calls to adjust its
size (note that the use of brk/sbrk and a single “heap area” is not required to fulfill the contract of
malloc/realloc/free; they may also be implemented using mmap to reserve potentially non-contiguous
regions of virtual memory into the process’ virtual address space). The Heap area is shared by all shared
libraries and dynamically loaded modules in a process.
Examples:
The size(1) command reports the sizes (in bytes) of the text, data, and bss segments. ( for more details
please refer man page of size(1) )

STATIC MEMORY
- Static memory persists throughout the entire life of the program, and is usually used to store things
like global variables, or variables created with the static clause. For example:
int theforce;

- On many systems this variable uses 4 bytes of memory. This memory can come from one of two
places. If a variable is declared outside of a function, it is considered global, meaning it is accessible
anywhere in the program. Global variables are static, and there is only one copy for the entire program.
Inside a function the variable is allocated on the stack. It is also possible to force a variable to be static
using the static clause. For example, the same variable created inside a function using the static clause
would allow it to be stored in static memory.
static int theforce;

STACK MEMORY
- The stack is used to store variables used on the inside of a function (including the main() function). It’s
a LIFO, “Last-In,-First-Out”, structure. Every time a function declares a new variable it is “pushed” onto
the stack. Then when a function finishes running, all the variables associated with that function on the
stack are deleted, and the memory they use is freed up. This leads to the “local” scope of function
variables. The stack is a special region of memory, and automatically managed by the CPU – so you don’t
have to allocate or deallocate memory. Stack memory is divided into successive frames where each time a
function is called, it allocates itself a fresh stack frame.

- Note that there is generally a limit on the size of the stack – which can vary with the operating system
(for example OSX currently has a default stack size of 8MB). If a program tries to put too much
information on the stack, stack overflow will occur. Stack overflow happens when all the memory in the
stack has been allocated, and further allocations begin overflowing into other sections of memory. Stack
overflow also occurs in situations where recursion is incorrectly used.
A summary of the stack:

 the stack is managed by the CPU, there is no ability to modify it


 variables are allocated and freed automatically
 the stack it not limitless – most have an upper bound
 the stack grows and shrinks as variables are created and destroyed
 stack variables only exist whilst the function that created them exists

HEAP MEMORY
The heap is the diametrical opposite of the stack. The heap is a large pool of memory that can be used
dynamically – it is also known as the “free store”. This is memory that is not automatically managed –
you have to explicitly allocate (using functions such as malloc), and deallocate (e.g. free) the memory.
Failure to free the memory when you are finished with it will result in what is known as a memory leak –
memory that is still “being used”, and not available to other processes. Unlike the stack, there are
generally no restrictions on the size of the heap (or the variables it creates), other than the physical size of
memory in the machine. Variables created on the heap are accessible anywhere in the program.
Oh, and heap memory requires you to use pointers.
A summary of the heap:

 the heap is managed by the programmer, the ability to modify it is somewhat boundless
 in C, variables are allocated and freed using functions like malloc() and free()
 the heap is large, and is usually limited by the physical memory available
 the heap requires pointers to access it

A header file is a file with extension .h which contains C function declarations and macro definitions to
be shared between several source files. There are two types of header files: the files that the programmer
writes and the files that comes with your compiler.
You request to use a header file in your program by including it with the C preprocessing
directive #include, like you have seen inclusion of stdio.h header file, which comes along with your
compiler.
Including a header file is equal to copying the content of the header file but we do not do it because it will
be error-prone and it is not a good idea to copy the content of a header file in the source files, especially if
we have multiple source files in a program.
A simple practice in C or C++ programs is that we keep all the constants, macros, system wide global
variables, and function prototypes in the header files and include that header file wherever it is required.

You might also like