Author: saqibkhan

  • Compilation Process in C

    C is a compiled language. Compiled languages provide faster execution performance as compared to interpreted languages. Different compiler products may be used to compile a C program. They are GCC, Clang, MSVC, etc. In this chapter, we will explain what goes in the background when you compile a C program using GCC compiler.

    Compiling a C Program

    A sequence of binary instructions consisting of 1 and 0 bits is called as machine code. High-level programming languages such as C, C++, Java, etc. consist of keywords that are closer to human languages such as English. Hence, a program written in C (or any other high-level language) needs to be converted to its equivalent machine code. This process is called compilation.

    Note that the machine code is specific to the hardware architecture and the operating system. In other words, the machine code of a certain C program compiled on a computer with Windows OS will not be compatible with another computer using Linux OS. Hence, we must use the compiler suitable for the target OS.

    Compilation

    C Compilation Process Steps

    In this tutorial, we will be using the gcc (which stands for GNU Compiler Collection). The GNU project is a free-software project by Richard Stallman that allows developers to have access to powerful tools for free.

    The gcc compiler supports various programming languages, including C. In order to use it, we should install its version compatible with the target computer.

    The compilation process has four different steps −

    • Preprocessing
    • Compiling
    • Assembling
    • Linking

    The following diagram illustrates the compilation process.

    Compilation Process

    Example

    To understand this process, let us consider the following source code in C languge (main.c) −

    #include <stdio.h>intmain(){/* my first program in C */printf("Hello World! \n");return0;}

    Output

    Run the code and check its output −

    Hello World!
    

    The “.c” is a file extension that usually means the file is written in C. The first line is the preprocessor directive #include that tells the compiler to include the stdio.h header file. The text inside /* and */ are comments and these are useful for documentation purpose.

    The entry point of the program is the main() function. It means the program will start by executing the statements that are inside this functions block. Here, in the given program code, there are only two statements: one that will print the sentence “Hello World” on the terminal, and another statement that tells the program to “return 0” if it exited or ended correctly. So, once we compiled it, if we run this program we will only see the phrase “Hello World” appearing.

    What Goes Inside the C Compilation Process?

    In order for our “main.c” code to be executable, we need to enter the command “gcc main.c”, and the compiling process will go through all of the four steps it contains.

    Step 1: Preprocessing

    The preprocessor performs the following actions −

    • It removes all the comments in the source file(s).
    • It includes the code of the header file(s), which is a file with extension .h which contains C function declarations and macro definitions.
    • It replaces all of the macros (fragments of code which have been given a name) by their values.

    The output of this step will be stored in a file with a “.i” extension, so here it will be in “main.i“.

    In order to stop the compilation right after this step, we can use the option “-E” with the gcc command on the source file, and press Enter.

    gcc -E main.c
    

    Step 2: Compiling

    The compiler generates the IR code (Intermediate Representation) from the preprocessed file, so this will produce a “.s” file. That being said, other compilers might produce assembly code at this step of compilation.

    We can stop after this step with the “-S” option on the gcc command, and press Enter.

    gcc -S main.c
    

    This is what the main.s file should look like −

    .file	"helloworld.c".text
       .def	__main;.scl	2;.type	32;.endef
       .section .rdata,"dr".LC0:.ascii "Hello, World! \0".text
       .globl	main
       .def	main;.scl	2;.type	32;.endef
       .seh_proc	main
    main:
       pushq	%rbp
       .seh_pushreg	%rbp
       movq	%rsp,%rbp
       .seh_setframe	%rbp,0
       subq	$32,%rsp
       .seh_stackalloc	32.seh_endprologue
       call	__main
       leaq	.LC0(%rip),%rcx
       call	puts
       movl	$0,%eax
       addq	$32,%rsp
       popq	%rbp
       ret
       .seh_endproc
       .ident	"GCC: (x86_64-posix-seh-rev0, Built by MinGW-W64 project) 8.1.0".def	puts;.scl	2;.type	32;.endef
    

    Step 3: Assembling

    The assembler takes the IR code and transforms it into object code, that is code in machine language (i.e. binary). This will produce a file ending in “.o”.

    We can stop the compilation process after this step by using the option “-c” with the gcc command, and pressing Enter.

    Note that the “main.o” file is not a text file, hence its contents won’t be readable when you open this file with a text editor.

    Step 4: Linking

    The linker creates the final executable, in binary. It links object codes of all the source files together. The linker knows where to look for the function definitions in the static libraries or the dynamic libraries.

    Static libraries are the result of the linker making a copy of all the used library functions to the executable file. The code in dynamic libraries is not copied entirely, only the name of the library is placed in the binary file.

    By default, after this fourth and last step, that is when you type the whole “gcc main.c” command without any options, the compiler will create an executable program called main.out (or main.exe in case of Windows) that we can run from the command line.

    We can also choose to create an executable program with the name we want, by adding the “-o” option to the gcc command, placed after the name of the file or files we are compiling.

    gcc main.c -o hello.out
    

    So now we could either type “./hello.out” if you didnt use the “-o” option or “./hello” to execute the compiled code. The output will be “Hello World” and following it, the shell prompt will appear again.

  • Hello World

    Every learner aspiring to become a professional software developer starts with writing a Hello World program in the programming language he/she is learning. In this chapter, we shall learn how to write a Hello World program in C language.

    Hello World in C Language

    Before writing the Hello World program, make sure that you have the C programming environment set up in your computer. This includes the GCC compiler, a text editor, and preferably an IDE for C programming such as CodeBlocks.

    Example

    The first step is to write the source code for the Hello World program. Open a text editor on your computer. On Windows, open Notepad or Notepad++, enter the following code and save it as “hello.c”.

    #include <stdio.h>intmain(){/* my first program in C */printf("Hello World! \n");return0;}

    Output

    Run the code and check its output −

    Hello World!
    

    The Step-by-Step Execution of a C Program

    Let us understand how the above program works in a step-by-step manner.

    Step 1

    The first statement in the above code is the #include statement that imports the stdio.h file in the current C program. This is called a preprocessor directive. This header file contains the definitions of several library functions used for stand IO operations. Since we shall be calling the printf() function which is defined in the stdio.h library, we need to include it in the first step.

    Step 2

    Every C program must contain a main() function. The main() function in this program prints the “Hello World” message on the console terminal.

    Inside the main() function, we have inserted a comment statement that is ultimately ignored by the compiler; it is for the documentation purpose.

    The next statement calls the printf() function. In C, every statement must terminate with a semicolon symbol (;), failing which the compiler reports an error.

    The printf() function, imported from the stdio.h library file, echoes the Hello World string to the standard output stream. In case of Windows, the standard output stream is the Command prompt terminal and in case of Linux it is the Linux terminal.

    In C, every function needs to have a return value. If the function doesnt return anything, its value is void. In the example above, the main() function has int as its return value. Since the main() function doesnt need to return anything, it is defined to return an integer “0”. The “return 0” statement also indicates that the program has been successfully compiled and run.

    Step 3

    Next, we need to compile and build the executable from the source code (“hello.c”).

    If you are using Windows, open the command prompt in the folder in which “hello.c” has been saved. The following command compiles the source code −

    gcc -c hello.c -o hello.o
    

    The -c option specifies the source code file to be compiled. This will result in an object file with the name hello.o if the C program doesnt have any errors. If it contains errors, they will be displayed. For example, if we forget to put the semicolon at the end of the printf() statement, the compilation result will show the following error −

    helloworld.c: In function 'main':
    helloworld.c:6:30: error: expected ';' before 'return'printf("Hello, World! \n")^;
    helloworld.c:8:4:return0;

    To build an executable from the compiled object file, use the following command −

    gcc  -o hello.exe hello.o
    

    The hello.exe is now ready to be run from the command prompt that displays the Hello World message in the terminal.

    C:\Users\user>hello
    Hello World!

    On Ubuntu Linux, the object file is first given executable permission before running it by prefixing “./” to it.

    $ chmod a+x a.o
    $ ./a.o
    

    You can also use an IDE such as CodeBlocks to enter the code, edit, debug and run the Hello World program more conveniently.

    Using CodeBlocks IDE for C Programming

    CodeBlocks is one the most popular IDEs for C/C++ development. Install it if you have not already done and open it. Create a new file from the File menu, enter the following code and save it as “hello.c”.

    Example

    #include <stdio.h>intmain(){/* my first program in C */printf("Hello World! \n");return0;}

    Output

    Run the code and check its output −

    Hello World!
    

    Choose Build and Run option from the Build menu as shown below −

    Build Menu

    You can also use the F9 shortcut for the same. If the program is error-free, the Build Log tab shows the following messages −

    gcc.exe   -c C:\Users\mlath\hello.c -o C:\Users\mlath\hello.o
    gcc.exe  -o C:\Users\mlath\hello.exe C:\Users\mlath\hello.o   
    Process terminated with status 0(0minute(s),0second(s))0error(s),0warning(s)(0minute(s),0second(s))
     
    Checking for existence: C:\Users\mlath \hello.exe
    Executing:'"C:\Program Files\CodeBlocks/cb_console_runner.exe" "C:\Users\mlath\hello.exe"'(in 'C:\Users\mlath\Documents')

    In a separate command prompt window, the output will be displayed −

    Hello World!
    
    Process returned 0(0x0)   execution time :0.236 s
    Press any key to continue.

    If the code contains errors, the build log tab echoes them. For instance, if we miss the trailing semicolon in the printf() statement, the log will be as below −

    Build Messages

    You can use any other IDE to run the C program. You will need to follow the documentation of the respective IDE for the purpose.

    Running the Hello World successfully also confirms that the C programming environment is working properly on your computer.

  • 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 Preprocessor Section

    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.

    The following statement defines a constant PI −

    #define PI 3.14159

    Example

    Once a constant is defined, it can be used in the rest of the C program.

    #include <stdio.h>#define PI 3.14159intmain(){int radius =5;float area = PI*radius*radius;printf("Area: %f", area);return0;}

    Output

    On executing this code, you will get the following output −

    Area: 78.539749
    

    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

    #include <stdio.h>#define PI 3.14159#define AREA(r) (PI*r*r)intmain(){int radius =5;float area =AREA(radius);printf("Area: %f", area);return0;}

    Output

    Area: 78.539749
    

    Macros are generally faster in execution than the functions.

    The main() Function

    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.

    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 doesnt 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

    A typical example of main() function is as follows −

    #include <stdio.h>intmain(){/* my first program in C */printf("Hello, World! \n");return0;}

    Output

    On executing this code, you will get the following output −

    Hello, World! 
    

    The Global Declaration Section

    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.

    Example of global variable declaration −

    int total =0;float average =0.0;

    Example of forward declaration of a function −

    floatarea(float height,float width);

    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.

    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 doesnt 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 cant be given in a line that starts with “//”. Hence, the following statement is erroneous:

    // Variable to store age. int age=20;

    Structure of the C Program

    The following code shows the different sections in a C program −

    /*Headers*/#include <stdio.h>#include <math.h>/*forward declaration*/floatarea_of_square(float);/*main function*/intmain(){/* my first program in C */float side =5.50;float area =area_of_square(side);printf("Side=%5.2f Area=%5.2f", side, area);return0;}/*subroutine*/floatarea_of_square(float side){float area =pow(side,2);return area;}

    Output

    On executing this code, you will get the following output −

    Side= 5.50 Area=30.25
    
  • 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 −

    GNU Compiler Collection (GCC) − GCC is a popular open-source C compiler. It is available for a wide range of platforms including Windows, macOS, and Linux. GCC is known for its wide range of features and support for a variety of C standards.

    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.

    Turbo C − Turbo C is a discontinued C compiler that was developed by Borland. It was popular in the early 1990s, but it is no longer widely used.

    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.

    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++.

    Xcode is currently available at developer.apple.com/technologies/tools/

    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.

    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 −

    gcc -c hello.c -o hello.o
    gcc -o hello.exe hello.o
    

    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.

    For Windows, download codeblocks-20.03mingw-setup.exe from https://www.codeblocks.org/downloads/binaries/ URL. This will install CodeBlocks as well as MinGW compiler on your computer. During the installation process, choose MinGW as the compiler to use.

    Example

    After the installation is complete, launch it and enter the following code −

    #include <stdio.h>intmain(){/* my first program in C */printf("Hello, World! \n");return0;}

    Output

    On executing this code, you will get the following output −

    Hello, World! 
    

    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.

    Hello World
  • Standards (ANSI, ISO, C99, C11, C17)

    A programming language standard is typically a set of specifications that precisely define the programming language syntax and semantics (i.e., the rule of writing the code, what the code means and how it behaves when executed).

    The C programming language standard defines the behavior of the program, i.e., How the program will ideally runWhat are the correct ways and definitions of some in-built functions? The standard works as a definitive “contract” between the programmers and the language implementers to ensure a certain level of consistency on how a language should work across different software.

    Standardized Versions of C Programming Language

    Some of the most commonly used C Standards are listed below −

    • C89 / ANSI C (1989) – C90 (ISO 1990) − It was the first standardized versions of the C languageIn this, version new features were added such as function prototypes, standard library, const, volatile, enum.
    • C95 Amendment − Introduced wide character library (h) for better support of international character sets, and provided iso646.h to provide alternative spellings for C operators (like and, or, not) to improve code readability and portability.
    • C99 (1999) − Introduced several new features lncluded long long int, stdbool.h, variable length arrays, flexible array members, inline functions, complex numbers, and // comments.
    • C11 (2011) − It introduced several new features including _Generic, static_assert, and the atomic type qualifier <stdatomic.h>, also addition of multithreading <threads.h>, Unicode (char16_t, char32_t) and memory manipulation.
    • C17 (2017/2018) − In this version, only bug fixes to C11, no new features were added.
    • C18 (2018) − Maintenance release, identical to C17 in practice.
    • C23 (latest) − It is the latest version of C that better supports the const qualifier and addition of the new keywords, attributes, typeof, improved Unicode, and contracts.

    The following table compares and contrasts the important features of different C standards −

    FeaturesK&R CC89/C90C99C11C17/C18C23
    Function PrototypeNoYesYesYesYesYes
    // CommentsNoNoYesYesYesYes
    Long long intNoNoYesYesYesYes
    MultithreadingNoNoNoYesYesYes
    AtomicsNoNoNoYesYesYes
    Unicode SupportNoNoLimitedYesYesYes

    Advantages of Having Standards in Programming Languages

    It is important to have Standards because they ensure uniformity in Syntax and Semantics, and reduce ambiguity by promoting consistency in any programming language −

    • Syntax − The grammatical rules that make a meaning and create valid programs by combining the statement keywords and symbols.
    • Semantics − Semantics are the set of rules that determines the meaning and execution behavior of the code written in the language. This includes the control flow of the programs how data is processed, and how memory is managed.
    • Consistency − The standard makes sure that different compilers and interpreters for the same language give consistent results, making code more portable and predictable.
    • Ambiguity Reduction − Ambiguity is something that can be understood in more than one way. In the C programming language, where the compiler cannot uniquely identify which specific identity (like a function, variable, or member) is being referred to due to multiple possible interpretations, it is ambiguity.

    By providing precise definition and standards, which minimize ambiguities and undefined behavior, one can avoid different interpretations or errors when running the code.

    Role of ANSI and ISO in C standardization

    In the early days (k&R C), different compilers (AT&TDECHP, etc.) implemented their own versions of C. It caused incompatibility: a program written for one compiler often would not compile and behave the same way on another. Therefore, C needed a formal standard to ensure that a program would have portability, reliability, and consistency.

    ANSI’s Role (American National Standards Institute)

    ANSI formed the X3J11 committee in 1983 to develop the standard specification for the C language. After the Several years of work they published C89 (ANSI C in 1989). After the development of C89 the ANSI C become the foundation on which all future was built.

    Following is the key contribution of the ANCI C (C89):

    • Defined function prototypes and type checking.
    • Introduced const, volatile, signed, and void
    • Standardized the C Standard Library (h, stdlib.h, string.h, etc.).
    • Removed ambiguities from K&R C, making C more portable.

    ISO’s Role (International Organization for Standardization)

    The standard was submitted to the ISO/IEC JTC1/SC22/WG14 committee after the ANSI published C89. So, ISO adopted ANSI C in 1990, with the minor changes known as C90.

    ISO became the prime authority responsible for maintaining and revising the C language standard (C95C99C11C17C18C23). ISO ensures that the standard is globally recognized, so C remain platform-independent and works with a wide range of compilers and operating systems.

    Relationship between ANSI and ISO

    ANSI is a national standard; it is US based. In contrast, ISO is international standard; it is a global standard. The version C89 (ANSI) and C90 (ISO) are essentially the same standard, with only minor editorial differences.

    Nowadays, most people refer to the ISO versions (C99, C11, C17, C23), but the foundation was laid by ANSI’s work.

    Importance of Standards in Real-World Applications

    Standards offer the following advantages in real-world application scenarios −

    • Ensure portability of code across platforms − Standardized C make sure that the same code runs on the different compilers, and hardware without modifications.
    • Help large teams and open-source projects avoid inconsistencies − A common standard prevents teams from writing compiler-specific code, making collaboration and code sharing easier.
    • Provide backward compatibility − New standards retain of the older features, so legacy programs can still compile and run on modern compilers.

    Conclusion

    The C standards introduced by the ANSI and ISO make the C language portable, reliable, and consistent across platforms. Each version, from C89 to C17, improved its features while keeping backward compatibility. Standardization ensures that C remains widely used in educational institutions, industry, and system programming, making it a powerful and stable language.

  • History of C Language

    C programming is a general-purpose, procedure-oriented programming language. It is both machine-independent and structured. C is a high-level programming language developed by Dennis Ritchie in the early 1970s. It is now one of the most popular and influential programming languages worldwide.

    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 JavaPHPJavaScriptC#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.

    Year wise development of programming is as follows −

    C Language History

    Overview of C Language History

    A brief overview of C language history is given below −

    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

    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.

    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

    Dennis Ritchie commenced development on C in 1971 and, in collaboration with other developers at Bell Labs, proceeded to refine it. The language was developed with portability, simplicity, and efficiency in mind, rendering it applicable to both application and system programming.

    History of C Versions After Traditional C

    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.

    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.

  • Features of C Programming Language

    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.

    C is a Procedural and Structured Language

    C is described as procedure-oriented and structured programming language. It is procedural because a C program is a series of instructions that explain the procedure of solving a given problem. It makes the development process easier.

    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.

    Some of the common applications of C programming include the development of Operating Systems, databases, device drivers, etc.

    C is a Fast Programming Language

    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

    Another feature of the C language is its portability. C programs are machine-independent which means that you can compile and run the same code on various machines with none or some machine-specific changes.

    C programming provides the functionality of using a single code on multiple systems depending on the requirement.

    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.

    C is a Mid-Level Programming Language

    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.

    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.

    Recursion in C programming provides the functionality of code reusability and backtracking.

    User-defined Data Types in C

    C has three basic data types in intfloat 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.

  • Overview

    C is a general−purpose, high−level language that was originally developed by Dennis M. Ritchie to develop the UNIX operating system at Bell Labs. C was originally first implemented on the DEC PDP-11 computer in 1972.

    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
    • 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 invented to write an operating system called UNIX.
    • C is a successor of B language which was introduced around the early 1970s.
    • The language was formalized in 1988 by the American National Standard Institute (ANSI).
    • The UNIX OS was totally written in C.
    • Today C is the most widely used and popular System Programming Language.
    • Most of the state-of-the-art software have been implemented using C.
    • Today’s most popular Linux OS and RDBMS MySQL have been written in C.

    Why Use C Language?

    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.

    Some examples of the use of C might be −

    • 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.

    It provides fine-grained control over hardware, making it highly efficient. As a result, C is commonly used to develop system−level programs, like designing Operating Systems, OS kernels, etc., and also used to develop applications like Text Editors, Compilers, Network Drivers, etc.

    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

    The following are the 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 operationsstring 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 functionsloops, 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

    The following are the disadvantages/drawbacks of C language −

    • Manual Memory Management − C languages need manual memory management, where a developer has to take care of allocating and deallocating memory explicitly.
    • 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

    The following are the applications of C language −

    • System Programming − C language is used to develop system software which are close to hardware such as operating systems, firmware, language translators, etc.
    • Embedded Systems − C language is used in embedded system programming for a wide range of devices such as microcontrollers, industrial controllers, etc.
    • Compiler and Interpreters − C language is very common to develop language compilers and interpreters.
    • Database Systems − Since C language is efficient and fast for low-level memory manipulation. It is used for developing DBMS and RDBMS engines.
    • Networking Software − C language is used to develop networking software such as protocols, routers, and network utilities.
    • Game Development − C language is widely used for developing games, gaming applications, and game engines.
    • Scientific and Mathematical Applications − C language is efficient in developing applications where scientific computing is required. Applications such as simulations, numerical analysis, and other scientific computations are usually developed in C language.
    • Text Editor and IDEs − C language is used for developing text editors and integrated development environments such as Vim and Emacs.

    Getting Started with C Programming

    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 Header Files

    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>

    stdlib.h − Contains functions involving memory allocation, rand function, and other utility functions.

    #include <stdlib.h>

    math.h − Includes mathematical functions like sqrtsincos, etc.

    #include <math.h>

    string.h − Includes functions for manipulating strings, such as strcpystrlen, etc.

    #include <string.h>

    ctype.h − Functions for testing and mapping characters, like isalphaisdigit, etc.

    #include <ctype.h>

    stdbool.h − Defines the boolean data type and values true and false.

    #include <stdbool.h>

    time.h − Contains functions for working with date and time.

    #include <time.h>

    limits.h − Defines various implementation-specific limits on integer types.

    #include <limits.h>

    Macros and Constants

    Define any macros or constants that will be used throughout the program. Macros and constants are optional.

    Example

    #include <stdio.h>#define PI 3.14159intmain(){float radius =5.0;float area = PI * radius * radius;printf("Area of the circle: %f\n", area);return0;}
    Output
    Area of the circle: 78.539749
    

    Global Declarations in C

    Global declarations are optional:

    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>// Global variable declarationint globalVariable;intmain(){// Rest of the programreturn0;}

    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 −

    intmain(){float radius =5.0;float area = PI * radius * radius;printf("Area of the circle: %f\n", area);return0;}

    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>// Global function declarationvoidsamplefunction();intmain(){// Programming statementsreturn0;}// Global function definitionvoidsamplefunction(){// 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.

  • Software Maintenance Cost Factors

    There are two types of cost factors involved in software maintenance.

    These are

    • Non-Technical Factors
    • Technical Factors

    Non-Technical Factors

    Software Maintenance Cost Factors

    1. Application Domain

    • If the application of the program is defined and well understood, the system requirements may be definitive and maintenance due to changing needs minimized.
    • If the form is entirely new, it is likely that the initial conditions will be modified frequently, as user gain experience with the system.

    2. Staff Stability

    • It is simple for the original writer of a program to understand and change an application rather than some other person who must understand the program by the study of the reports and code listing.
    • If the implementation of a system also maintains that systems, maintenance costs will reduce.
    • In practice, the feature of the programming profession is such that persons change jobs regularly. It is unusual for one user to develop and maintain an application throughout its useful life.

    3. Program Lifetime

    • Programs become obsolete when the program becomes obsolete, or their original hardware is replaced, and conversion costs exceed rewriting costs.

    4. Dependence on External Environment

    • If an application is dependent on its external environment, it must be modified as the climate changes.
    • For example:
    • Changes in a taxation system might need payroll, accounting, and stock control programs to be modified.
    • Taxation changes are nearly frequent, and maintenance costs for these programs are associated with the frequency of these changes.
    • A program used in mathematical applications does not typically depend on humans changing the assumptions on which the program is based.

    5. Hardware Stability

    • If an application is designed to operate on a specific hardware configuration and that configuration does not changes during the program’s lifetime, no maintenance costs due to hardware changes will be incurred.
    • Hardware developments are so increased that this situation is rare.
    • The application must be changed to use new hardware that replaces obsolete equipment.

    Technical Factors

    Technical Factors include the following:

    Software Maintenance Cost Factors

    Module Independence

    It should be possible to change one program unit of a system without affecting any other unit.

    Programming Language

    Programs written in a high-level programming language are generally easier to understand than programs written in a low-level language.

    Programming Style

    The method in which a program is written contributes to its understandability and hence, the ease with which it can be modified.

    Program Validation and Testing

    • Generally, more the time and effort are spent on design validation and program testing, the fewer bugs in the program and, consequently, maintenance costs resulting from bugs correction are lower.
    • Maintenance costs due to bug’s correction are governed by the type of fault to be repaired.
    • Coding errors are generally relatively cheap to correct, design errors are more expensive as they may include the rewriting of one or more program units.
    • Bugs in the software requirements are usually the most expensive to correct because of the drastic design which is generally involved.

    Documentation

    • If a program is supported by clear, complete yet concise documentation, the functions of understanding the application can be associatively straight-forward.
    • Program maintenance costs tends to be less for well-reported systems than for the system supplied with inadequate or incomplete documentation.

    Configuration Management Techniques

    • One of the essential costs of maintenance is keeping track of all system documents and ensuring that these are kept consistent.
    • Effective configuration management can help control these costs.

  • Causes of Software Maintenance Problems

    Causes of Software Maintenance Problems

    Lack of Traceability

    • Codes are rarely traceable to the requirements and design specifications.
    • It makes it very difficult for a programmer to detect and correct a critical defect affecting customer operations.
    • Like a detective, the programmer pores over the program looking for clues.
    • Life Cycle documents are not always produced even as part of a development project.

    Lack of Code Comments

    • Most of the software system codes lack adequate comments. Lesser comments may not be helpful in certain situations.

    Obsolete Legacy Systems

    • In most of the countries worldwide, the legacy system that provides the backbone of the nation’s critical industries, e.g., telecommunications, medical, transportation utility services, were not designed with maintenance in mind.
    • They were not expected to last for a quarter of a century or more!
    • As a consequence, the code supporting these systems is devoid of traceability to the requirements, compliance to design and programming standards and often includes dead, extra and uncommented code, which all make the maintenance task next to the impossible.

    Software Maintenance Process

    Causes of Software Maintenance Problems

    Program Understanding

    The first step consists of analyzing the program to understand.

    Generating a Particular maintenance problem

    The second phase consists of creating a particular maintenance proposal to accomplish the implementation of the maintenance goals.

    Ripple Effect

    The third step consists of accounting for all of the ripple effects as a consequence of program modifications.

    Modified Program Testing

    The fourth step consists of testing the modified program to ensure that the revised application has at least the same reliability level as prior.

    Maintainability

    Each of these four steps and their associated software quality attributes is critical to the maintenance process. All of these methods must be combined to form maintainability.