C Notes
C Notes
C is popular for its simplicity, efficiency, and versatility. It has powerful features including
low-level memory access, a rich set of operators, and a modular framework.
Apart from its importance with respect to the evolution of computer programming
technologies, the design of C language has a profound influence on most of the other
programming languages that are in use today. The languages that are influenced by C include
Java, PHP, JavaScript, C#, Python and many more. These languages have designed their
syntax, control structures and other basic features from C.
C supports different hardware and operating systems due to its portability. Generally, it is
considered as a basic language and influenced many other computer languages. It is most
widely used in academia and industry. C's relevance and extensive acceptance make it crucial
for prospective programmers.
The history of the C programming language is quite fascinating and pivotal in the
development of computer science and software engineering.
Origin of C Programming
'ALGOL' was the foundation or progenitor of programming languages. It was first introduced
in 1960. 'ALGOL' was widely used in European countries. The ALGOL had introduced the
concept of structured programming to the developer community. The year 1967 marked the
introduction of a novel computer programming language known as 'BCPL', an acronym for
Basic Combined Programming Language. BCPL was designed by Martin Richards in the
mid-1960s.
Dennis Ritchie created C at Bell Laboratories in the early 1970s. It developed from an older
language named B that Ken Thompson created. The main purpose of C's creation was to
construct the Unix operating system, which was crucial in the advancement of contemporary
computers. BCPL, B, and C all fit firmly in the traditional procedural family typified by
Fortran and Algol 60. BCPL, B and C differ syntactically in many details, but broadly they
are similar.
Page 1 of 18
Development of C Programming
In 1971, Dennis Ritchie started working on C, and he and other Bell Labs developers kept
improving it. The language is appropriate for both system programming and application
development because it was made to be straightforward, effective, and portable.
Standardization of C Programming
K&R C
Dennis Ritchie along with Brian Kernighan published the first edition of their book "The C
Programming Language". Popularly known as K&R (the initials of its authors), the book
served for many years as an informal specification of the language. The version of C that it
describes is commonly referred to as "K&R C". It is also referred to as C78.
Many of the features of C language introduced in K&R C are still the part of the language
ratified as late as in 2018. In early versions of C, only functions that return types other than
int must be declared if used before the function definition; functions used without prior
declaration were presumed to return type int.
C compilers by AT&T and other vendors supported several features added to the K&R C
language. Although C started gaining popularity, there was a lack of uniformity in
implementation. Therefore, it was felt that the language specifications must be standardized.
ANSI C
In the 1980s, the American National Standards Institute (ANSI) began working on a formal
standard for the C language. This led to the development of ANSI C, which was standardized
in 1989. ANSI C introduced several new features and clarified ambiguities present in earlier
versions of the language.
C89/C90
The ANSI C standard was adopted internationally and became known as C89 (or C90,
depending on the year of ratification). It served as the basis for compilers and development
tools for many years.
C99
In 1999, the ISO/IEC approved an updated version of the C standard known as C99. The C
standard was further revised in the late 1990s.
Page 2 of 18
C99 introduced new features, including inline functions, several new data types such as a
complex type to represent complex numbers, and variable-length arrays etc. It also added
support for C++ style one-line comments beginning with //.
C11
C11, published in 2011, is another major revision of the C standard. The C11 standard adds
new features to C and the library and introduced features such as multi-threading support,
anonymous structures and unions, and improved Unicode support.
It includes type generic macros, anonymous structures, improved Unicode support, atomic
operations, multi-threading, and bounds-checked functions. It has an improved compatibility
with C++.
C17
The C17 standard has been published in June 2018. C17 is the current standard for the C
programming language. No new features have been introduced with this standard revision. It
only performs certain technical corrections, and clarifications to defects in C11.
C18
The most recent version of the C standard, C18, was published in 2018. It includes minor
revisions and bug fixes compared to C11.
C23
C23 is the informal name for the next major C language standard revision, expected to be
published in 2024. 14 new keywords are expected to be introduced in this revision.
C has remained popular over time because to its simplicity, efficiency, and versatility. It has
been used to create a diverse spectrum of software including operating systems, embedded
systems, applications, and games. C's syntax and semantics have also impacted different
modern programming languages such as C++, Java, and Python.
C Language - Overview
In 1978, Brian Kernighan and Dennis Ritchie produced the first publicly available description
of C, now known as the K&R standard.
The UNIX operating system, the C compiler, and essentially all UNIX application programs
have been written in C. C has now become a widely used professional language for various
reasons −
Easy to learn
Page 3 of 18
Structured language
It produces efficient programs
It can handle low−level activities
It can be compiled on a variety of computer platforms
Facts about C
C was initially used for system development work, particularly the programs that make-up
the operating system. C was adopted as a system development language because it produces
code that runs nearly as fast as the code written in assembly language.
Operating Systems
Language Compilers
Assemblers
Text Editors
Print Spoolers
Network Drivers
Modern Programs
Databases
Language Interpreters
Utilities
C covers all the basic concepts of programming. It's a base or mother programming language
to learn object−oriented programming like C++, Java, .Net, etc. Many modern programming
languages such as C++, Java, and Python have borrowed syntax and concepts from C.
Page 4 of 18
C programs are portable; hence they can run on different platforms without significant
modifications.
C has played a pivotal role as a fundamental programming language over the course of
programming history. However, its popularity for application development has somewhat
diminished in comparison to more contemporary languages. This may be attributed to its
low−level characteristics and the existence of higher−level languages that offer a greater
abundance of pre−existing abstractions and capabilities. Nevertheless, the use of the
programming language C remains indispensable in domains where factors such as optimal
performance, meticulous management of system resources, and the imperative need for
portability hold utmost significance.
Advantages of C Language
Efficiency and speed − C is known for being high−performing and efficient. It can
let you work with memory at a low level, as well as allow direct access to hardware,
making it ideal for applications requiring speed and economical resource use.
Portable − C programs can be compiled and executed on different platforms with
minimal or no modifications. This portability is due to the fact that the language has
been standardized and compilers are available for use on various operating systems
globally.
Close to Hardware − C allows direct manipulation of hardware through the use of
pointers and low−level operations. This makes it suitable for system programming
and developing applications that require fine-grained control over hardware resources.
Standard Libraries − For common tasks such as input/output operations, string
manipulation, and mathematical computations, C comes with a large standard library
which helps developers write code more efficiently by leveraging pre−built functions.
Structured Programming − C helps to organize code into modular and
easy−to−understand structures. With functions, loops, and conditionals, developers
can produce clear code that is easy to maintain.
Procedural Language − C follows a procedural paradigm that is often simpler and
more straightforward for some types of programming tasks.
Versatility − C language is a versatile programming language and it can be used for
various types of software such as system applications, compilers, firmware,
application software, etc.
Drawbacks of C Language
Page 5 of 18
No Object−Oriented Feature − Nowadays, most of the programming languages
support the OOPs features. But C language does not support it.
No Garbage Collection − C language does not support the concept of Garbage
collection. A developer needs to allocate and deallocate memory manually and this
can be error-prone and lead to memory leaks or inefficient memory usage.
No Exception Handling − C language does not provide any library for handling
exceptions. A developer needs to write code to handle all types of expectations.
Applications of C Language
To learn C effectively, we need to understand its structure first. Every programming language
has its programming structure. A typical structure of a C program includes several parts. The
following steps show the C structure of a regular C program−
Include necessary header files that contain declarations of functions, constants, and macros
that can be used in one or more source code files. Some popular header files are as −
stdio.h − Provides input and output functions like printf and scanf.
#include <stdio.h>
Page 6 of 18
stdlib.h − Contains functions involving memory allocation, rand function, and other utility
functions.
#include <stdlib.h>
string.h − Includes functions for manipulating strings, such as strcpy, strlen, etc.
#include <string.h>
ctype.h − Functions for testing and mapping characters, like isalpha, isdigit, etc.
#include <ctype.h>
stdbool.h − Defines the boolean data type and values true and false.
#include <stdbool.h>
Define any macros or constants that will be used throughout the program. Macros and
constants are optional.
Example
Open Compiler
#include <stdio.h>
#define PI 3.14159
int main() {
float radius = 5.0;
float area = PI * radius * radius;
Output
Area of the circle: 78.539749
Global Declarations in C
Page 7 of 18
int globalVariable;
void sampleFunction();
Declare global variables and functions that will be used across different parts of the program.
Take a look at the following example −
#include <stdio.h>
int main()
{
// Rest of the program
return 0;
}
Main Function
Every C program must have a main function. It is the entry point of the program. Take a look
at the following example −
int main() {
float radius = 5.0;
float area = PI * radius * radius;
Functions in C
Define other functions as needed. The main function may call these functions. Take a look at
the following example:
#include <stdio.h>
int main() {
// Programming statements
return 0;
}
Page 8 of 18
// Function programming statements implementation
}
A C program can vary from 3 lines to millions of lines and it should be written into one or
more text files with extension ".c"; for example, hello.c. You can use "vi", "vim" or any
other text editor to write your C program into a file.
This tutorial assumes that you know how to edit a text file and how to write source code
inside a program file.
C - Environment Setup
To start learning programming in C, the first step is to setup an environment that allows you
to enter and edit the program in C, and a compiler that builds an executable that can run on
your operating system. You need two software tools available on your computer, (a) The C
Compiler and (b) Text Editor.
The C Compiler
The source code written in the source file is the human readable source for your program. It
needs to be "compiled", into machine language so that your CPU can actually execute the
program as per the instructions given.
There are many C compilers available. Following is a select list of C compilers that are
widely used −
Clang: Clang is an open-source C compiler that is part of the LLVM project. It is available
for a variety of platforms including Windows, macOS, and Linux. Clang is known for its
speed and optimization capabilities.
Microsoft Visual C++ − Microsoft Visual C++ is a proprietary C compiler that is developed
by Microsoft. It is available for Windows only. Visual C++ is known for its integration with
the Microsoft Visual Studio development environment.
The examples in this tutorial are compiled on the GCC compiler. The most frequently used
and free available compiler is the GNU C/C++ compiler. The following section explains how
to install GNU C/C++ compiler on various operating systems. We keep mentioning C/C++
together because GNU gcc compiler works for both C and C++ programming languages.
Page 9 of 18
Installation on UNIX/Linux
If you are using Linux or UNIX, then check whether GCC is installed on your system by
entering the following command from the command line −
$ gcc -v
If you have GNU compiler installed on your Ubuntu Linux machine, then it should print a
message as follows −
$ gcc -v
Using built-in specs.
COLLECT_GCC=gcc
COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-linux-gnu/11/lto-wrapper
OFFLOAD_TARGET_NAMES=nvptx-none:amdgcn-amdhsa
OFFLOAD_TARGET_DEFAULT=1
Target: x86_64-linux-gnu
Configured with: ../src/configure -v . . .
Thread model: posix
Supported LTO compression algorithms: zlib zstd
gcc version 11.3.0 (Ubuntu 11.3.0-1ubuntu1~22.04)
If GCC is not installed, then you will have to install it yourself using the detailed instructions
available at https://gcc.gnu.org/install/
Installation on Mac OS
If you use Mac OS X, the easiest way to obtain GCC is to download the Xcode development
environment from Apple's web site and follow the simple installation instructions. Once you
have Xcode setup, you will be able to use GNU compiler for C/C++.
Installation on Windows
To install GCC on Windows, you need to install MinGW. To install MinGW, go to the
MinGW downloads page, https://www.mingw-w64.org/downloads/, and follow the link to
the MinGW download page. Download the latest version of the MinGW installation program,
mingw-w64-install.exe from here.
While installing Min GW, at a minimum, you must install gcc-core, gcc-g++, binutils, and
the MinGW runtime, but you may wish to install more.
Add the bin subdirectory of your MinGW installation to your PATH environment variable,
so that you can specify these tools on the command line by their simple names.
After the installation is complete, you will be able to run gcc, g++, ar, ranlib, dlltool, and
several other GNU tools from the Windows command line.
Page 10 of 18
Text Editor
You will need a Text Editor to type your program. Examples include Windows Notepad, OS
Edit command, Brief, Epsilon, EMACS, and vim or vi.
The name and version of the text editors can vary on different operating systems. For
example, Notepad will be used on Windows, and vim or vi can be used on windows as well
as on Linux or UNIX.
The files you create with your editor are called the source files and they contain the program
source codes. The source files for C programs are typically named with the extension ".c".
Before starting your programming, make sure you have one text editor in place and you have
enough experience to write a computer program, save it in a file, compile it and finally
execute it.
Using an IDE
Using a general-purpose text editor such as Notepad or vi for program development can be
very tedious. You need to enter and save the program with ".c" extension (say "hello.c"), and
then compile it with the following command −
The executable file is then run from the command prompt to obtain the output. However, if
the source code contains errors, the compilation will not be successful. Hence we need to
repeatedly switch between the editor program and command terminal. To avoid this tedious
process, we should an IDE (Integrated Development Environment).
There are many IDEs available for writing, editing, debugging and executing C programs.
Examples are CodeBlocks, NetBeans, VSCode, etc.
CodeBlocks is a popular open-source IDE for C and C++. It is available for installation on
various operating system platforms like Windows, Linux, MacOS.
Example
After the installation is complete, launch it and enter the following code −
Open Compiler
#include <stdio.h>
int main() {
/* my first program in C */
Page 11 of 18
printf("Hello, World! \n");
return 0;
}
Output
From the Build menu, build and run the program (use F9 shortcut). The Build Log window
shows successful compilation messages. The output (Hello World) is displayed in a separate
command prompt terminal.
C - Program Structure
A typical program in C language has certain mandatory sections and a few optional sections,
depending on the program's logic, complexity, and readability. Normally a C program starts
with one or more preprocessor directives (#include statements) and must have a main()
function that serves as the entry point of the program. In addition, there may be global
declarations of variables and functions, macros, other user-defined functions, etc.
The C compiler comes with several library files, having ".h" as an extension. A ".h" file
(called a "header file") consists of one or more predefined functions (also called "library
functions") to be used in the C program.
The library functions must be loaded in any C program. The "#include" statement is used to
include a header file. It is a "preprocessor directive".
For example, printf() and scanf() functions are needed to perform console I/O operations.
They are defined in the stdio.h file. Hence, you invariably find #include <stdio.h> statement
at the top of any C program. Other important and frequently used header files include
string.h, math.h, stdlib.h, etc.
There are other preprocessor directives such as #define which is used to define constants and
macros and #ifdef for conditional definitions.
Page 12 of 18
The following statement defines a constant PI −
#define PI 3.14159
Example
Output
You can also define a macro with the "#define" directive. It is similar to a function in C. We
can pass one or more arguments to the macro name and perform the actions in the code
segment.
The following code defines AREA macro using the #define statement −
Example
Open Compiler
#include <stdio.h>
#define PI 3.14159
#define AREA(r) (PI*r*r)
int main(){
int radius = 5;
float area = AREA(radius);
printf("Area: %f", area);
return 0;
}
Output
Area: 78.539749
A C program is a collection of one or more functions. There are two types of functions in a C
program: library functions and user-defined functions.
Page 13 of 18
There must be at least one user-defined function in a C program, whose name must be
main(). The main () function serves as the entry point of the program. When the program is
run, the compiler looks for the main () function.
The main() function contains one or more statements. By default, each statement must end
with a semicolon. The statement may include variable declarations, decision control or loop
constructs or call to a library or another user-defined function.
In C, a function must have a data type. The data type of return value must match with the data
type of the function. By default, a function in C is of int type. Hence, if a function doesn’t
have a return statement, its type is int, and you may omit it in the function definition, but the
compiler issues a warning −
warning: return type defaults to 'int'
Example
Output
This section consists of declaration of variables to be used across all the functions in a
program. Forward declarations of user-defined functions defined later in the program as well
as user-defined data types are also present in the global section.
Subroutines in a C Program
There may be more than one user-defined functions in a C program. Programming best
practices require that the programming logic be broken down to independent and reusable
functions in a structured manner.
Page 14 of 18
Depending on the requirements, a C program may have one or more user-defined functions,
which may be called from the main() function or any other user-defined function as well.
Comments in a C Program
Apart from the programming elements of a C program such as variables, structures, loops,
functions, etc., the code may have a certain text inside "/* .. */" recognized as comments.
Such comments are ignored by the compiler.
Inserting comments in the code often proves to be helpful in documenting the program, and
in understanding as well as debugging the programming logic and errors.
If the /* symbol doesn’t have a matching */ symbol, the compiler reports an error:
"Unterminated comment".
A text between /* and */ is called as C-style comment, and is used to insert multi-line
comments.
/*
Program to display Hello World
Author: Tutorialspoint
Built with codeBlocks
*/
A single line comment starts with a double forward-slash (//) and ends with a new line. It may
appear after a valid C statement also.
int age = 20; // variable to store age
However, a valid statement can’t be given in a line that starts with "//". Hence, the following
statement is erroneous:
// Variable to store age. int age=20;
/*forward declaration*/
float area_of_square(float);
/*main function*/
int main() {
/* my first program in C */
float side = 5.50;
float area = area_of_square(side);
printf ("Side=%5.2f Area=%5.2f", side, area);
return 0;
}
Page 15 of 18
/*subroutine*/
float area_of_square(float side){
float area = pow(side,2);
return area;
}
Output
Dennis Ritchie and Ken Thompson developed the C programming language in 1972,
primarily to re-implement the Unix kernel. Because of its features such as low-level memory
access, portability and cross-platform nature etc., C is still extremely popular. Most of the
features of C have found their way in many other programming languages.
The development of C has proven to be a landmark step in the history of computing. Even
though different programming languages and technologies dominate today in different
application areas such as web development, mobile apps, device drivers and utilities,
embedded systems, etc., the underlying technologies of all of them are inspired by the
features of C language.
The utility of any technology depends on its important features. The features also determine
its area of application. In this chapter, we shall take an overview of some of the significant
features of C language.
In C, the logic of a process can be expressed in a structured or modular form with the use of
function calls. C is generally used as an introductory language to introduce programming to
school students because of this feature.
C is a General-Purpose Language
The C language hasn't been developed with a specific area of application as a target. From
system programming to photo editing software, the C programming language is used in
various applications.
Page 16 of 18
C is a compiler-based language which makes the compilation and execution of codes faster.
The source code is translated into a hardware-specific machine code, which is easier for the
CPU to execute, without any virtual machine, as some of the other languages like Java need.
The fact that C is a statically typed language also makes it faster compared to dynamically
typed languages. Being a compiler-based language, it is faster as compared to interpreter-
based languages.
C is Portable
C is Extensible
C is an extensible language. It means if a code is already written, you can add new features to
it with a few alterations. Basically, it allows adding new features, functionalities, and
operations to an existing C program.
Standard Libraries in C
Most of the C compilers are bundled with an extensive set of libraries with several built-in
functions. It includes OS-specific utilities, string manipulation, mathematical functions, etc.
Importantly, you can also create your user-defined functions and add them to the existing C
libraries. The availability of such a vast scope of functions and operations allows a
programmer to build a vast array of programs and applications using the C language.
Pointers in C
One of the unique features of C is its ability to manipulate the internal memory of the
computer. With the use of pointers in C, you can directly interact with the memory.
Pointers point to a specific location in the memory and interact directly with it. Using the C
pointers, you can interact with external hardware devices, interrupts, etc.
High-level languages have features such as the use of mnemonic keywords, user-defined
identifiers, modularity etc. C programming language, on the other hand, provides a low-level
access to the memory. This makes it a mid-level language.
As a mid-level programming language, it provides the best of both worlds. For instance, C
allows direct manipulation of hardware, which high-level programming languages do not
offer.
Page 17 of 18
C Has a Rich Set of Built-in Operators
C is perhaps the language with the most number of built-in operators which are used in
writing complex or simplified C programs. In addition to the traditional arithmetic and
comparison operators, its binary and pointer related operators are important when bit-level
manipulations are required.
Recursion in C
C language provides the feature of recursion. Recursion means that you can create a function
that can call itself multiple times until a given condition is true, just like the loops.
C has three basic data types in int, float and char. However, C programming has the
provision to define a data type of any combination of these three types, which makes it very
powerful.
In C, you can define structures and union types. You also have the feature of declaring
enumerated data types.
Preprocessor Directives in C
In C, we have preprocessor directives such as #include, #define, etc. They are not the
language keywords. Preprocessor directives in C carry out some of the important roles such
as importing functions from a library, defining and expanding the macros, etc.
File Handling in C
C language doesn't directly manipulate files or streams. Handling file IO is not a part of the C
language itself but instead is handled by libraries and their associated header files.
File handling is generally implemented through high-level I/O which works through streams.
C identifies stdin, stdout and stderr as standard input, output and error streams. These
streams can be directed to a disk file to perform read/write operations.
These are some of the important features of C language that make it one of the widely used
and popular computer languages.
Page 18 of 18