C Programming Notes

Lecture #1: Prelude

  • Course Objectives:
    • Acquire knowledge on solving logical problems using computing machines.
    • Map algorithmic solutions to C programming language constructs.
    • Gain knowledge about C constructs and its ecosystem.
    • Gain knowledge about issues with C Standards and their behaviors.
  • Course Outcomes:
    • Apply algorithmic solutions to counting problems using C Constructs.
    • Understand, analyze, and apply sorting and searching techniques.
    • Understand, analyze, and apply text processing and string manipulation using Arrays, Pointers, and functions.
    • Understand user-defined type creation and implement using C structures and unions.

Prelude

  • Q1. What is a Computer Programming Language (CPL)?
    • A set of rules converting strings or graphical elements to machine code.
    • An artificial language to control a machine's behavior, especially a computer.
    • Defined by syntactic and semantic rules to determine structure and meaning.
    • Used to implement algorithms.
    • Allows instructions to be given in a language the computer understands.
    • A formal language used to communicate instructions to a machine.
    • Used to create programs to control machine behavior.
  • Q2. Why CPL?
    • Advances the ability to develop real algorithms.
    • Provides features for Computer Programmers (CP).
    • Can be used effectively to get the best results.
    • Improves customization of current coding.
    • Simplifies programming with basic features for resourceful codes.
    • Offers flexibility in coding style, emphasizing concept clarity.
  • Q3. Why so many Programming Languages?
    • To choose the right language for a specific problem domain.
    • Examples: Web Browsers, Social Networks, Games, Operating Systems.
  • Q4. What are the different Levels of Programming Language?
    • Low Level:
      • Binary codes executed by the CPU.
      • Requires more responsibility from the programmer.
      • Machine Language.
    • Middle Level:
      • Offers basic data structures and array definition.
      • Requires programmers to manage operations.
      • C and C++.
    • High Level:
      • Programmer focuses on the algorithm and programming itself.
      • Java, Python, Pascal.
  • Q5. What is the meaning of Paradigm?
    • A programming paradigm is a style or way of programming.
      • Imperative: Explicit sequence of commands that update state (e.g., Python).
      • Declarative: Specifies the result, not how to get it (e.g., LISP, SQL).
      • Structured: Uses clean, goto-free, nested control structures (e.g., C Language).
      • Procedural: Imperative programming with procedure calls (e.g., C Language).
      • Functional (Applicative): Function calls that avoid global state (e.g., Scheme, Haskell, JavaScript).
      • Function-Level (Combinator): Programming with no variables at all (e.g., Scheme, Haskell, JavaScript).
      • Object-Oriented: Objects sending messages, with encapsulated state and public interfaces.
        • Class-based: Objects from classes.
        • Prototype-based: Objects from a prototype.
        • Examples: Java, C++, Python.
      • Event-Driven: Emitters and listeners of asynchronous actions.
      • Flow-Driven: Processes communicating over predefined channels.
      • Logic (Rule-based): Facts and rules; an engine infers answers.
      • Constraint: Specifying constraints; an engine finds values.
      • Aspect-Oriented: Cross-cutting concerns applied transparently.
      • Reflective: Manipulating program elements themselves.
      • Array: Powerful array operators making loops unnecessary.
  • Q6: Which Languages are used while Developing Whatsapp?
    • Erlang, JqGrid, Libphonenum, LightOpenId, PHP5, Yaws and many more
  • Q7. Why should one learn C? What are the advantages of ‘C’? Is not ‘C’ an outdated language?’
    • Every language has a philosophy. ‘C’ prioritizes efficiency, placing safety in the programmer's hands.
      • You get what you deserve. If you are lucky, the program crashes. Otherwise, something subtle may happen, which later may lead to catastrophic failures.
    • C gives importance to efficiency.
    • C is not very safe; you can make your program safe.
    • C is not very strongly typed; mixing of types may not result in errors.
    • C is the language of choice for all hardware related software.
    • C is the language of choice for software’s like operating system, compilers, linkers, loaders, device drivers.
  • Q8. Is ‘C’ not an old language?
    • Yes and No.
    • Designed by Dennis Ritchie. The language has evolved over a period. The latest ‘C’ was revised in 2011.
  • Q9. What is TIOBE Index?
    • “The Importance Of Being Earnest” - TIOBE.
    • TIOBE is an indicator of the popularity of programming languages.
    • The TIOBE index is updated once a month.
    • The ratings are based on the number of skilled engineers world-wide, courses and third party vendors.
    • Popular search engines are used.
    • It is not about the best programming language or the language in which most lines of code have been written.
  • Q10: What is the history of PLs?
    • 1820-1850: Charles Babbage invented the Analytical Engine and Difference Engine.
    • 1942: ENIAC used electrical signals.
    • 1945: Von Neumann developed shared program technique and conditional control transfer.
    • 1949: Short code appeared.
    • 1951: Grace Hopper wrote the first compiler, A-0.
    • Fortran: 1957, John Backus.
    • Lisp, Algol: 1958.
    • Cobol: 1959.
    • Pascal: 1968, Niklaus Wirth.
    • C: 1972, D Ritchie.
    • C++: 1983, Bjarne Stroustrup, Compile time type checking, templates are used.
    • Java: 1995, J. Gosling, Rich set of APIs and portable across platform through the use of JVM.
    • Development of C
      • Martin Richards, around 60’s developed BCPL.
      • Enhanced by Ken Thompson and Introduced B language.
      • C is originally developed between 1969 and 1973 at Bell Labs by Dennis Ritchie and Kernighan. Closely tied to the development of the Unix operating system.
      • Standardized by the ANSI since 1989 and subsequently by ISO.
        • ANSI C, C89, C99, C11, C17, or C23

Lecture #3: GCC, PDLC

  • Introduction to GCC
    • Richard Stallman is the original author of the GNU C Compiler, the founder of the GNU Project.
    • The GNU Project was started in 1984 to create a complete Unix-like operating system as free software.
    • The first release of gcc was made in 1987, as the first portable ANSI C optimizing compiler released as free software.
    • A major revision of the compiler came with the 2.0 series in 1992, which added the ability to compile C++.
    • The acronym gcc is now used to refer to the “GNU Compiler Collection”
    • GCC has been extended to support many additional languages, including Fortran, ADA, Java and Objective-C.
    • Its development is guided by the gcc Steering Committee.
  • Features of GCC:
    • A portable compiler, it runs on most platforms available today, and can produce output for many types of processors.
    • Supports microcontrollers, DSPs and 64-bit CPUs.
    • It is not only a native compiler, it can also cross-compile any program, producing executable files for a different system from the one used by gcc itself.
    • Allows software to be compiled for embedded systems.
    • Written in C with a strong focus on portability, and can compile itself, so it can be adapted to new systems easily.
    • It has multiple language frontends, for parsing different languages.
    • It can compile or cross-compile programs in each language, for any architecture Example: Can compile an ADA program for a microcontroller or a C program for a supercomputer.
    • It has a modular design, allowing support for new languages and architectures to be added.
    • It is free software, distributed under the GNU General Public License (GNU GPL).
    • gcc users have the freedom to share any enhancements and also make use of enhancements to gcc developed by others.
  • Installation of gcc on different Operating systems:
    • Windows OS – Installation of gcc using Mingw.
      • https://www.youtube.com/watch?v=sXW2VLrQ3Bs
    • Linux /MAC OS – gcc available by default
  • Program Development Life Cycle [PDLC] Phases involved in PDLC are Editing, Pre-processing, Compilation, Linking, Loading and execution.
    • Editing:
      • Entering the program into the computer.
      • Saving the source program (e.g., first.c).
    • Pre-Processing:
      • Macro substitution.
      • Comments are stripped off.
      • Expansion of included files.
    • The output is called a translation unit or translation.
      To understand Pre-processing better, compile the ‘first.c’ program using flag -E, which will print the pre-processed output to stdout. Command, gcc -E first.c
    • Compiling:
      • Converting the program from textual source code into machine code.
        Compiler processes statements written in a particular programming language and converts them into machine language or "code" that a computer's processor uses. The translation is compiled.
        Output of this command is first.o -> Object file. Command, gcc -c first.c
        Pre-processing and compiling.
        Machine code is then stored in a file known as an executable file. Translating and compiling.
        The output is called an object file.
        Automatically creates an object file whose name is the same as the source file, but with ‘.o’ instead of the original extension.
    • Linking:
      • Linking of function calls with their definitions.
      • The definition of printf() is resolved and the actual address of the function printf() is plugged in.
      • Putting together all the object files along with the predefined library routines by linking.
        *The output is called as image or a loadable image with the name a.out [linux based] or a.exe[windows] Command, gcc first.o -o PESU
        gcc first.o
        Loadable image - Output file name is PESU
      • If a file with the same name[a.out/a,exe] as the executable file already exists in the current directory it will be overwritten.
    • Executing:
      • Loader loads the image into the memory of the computer.
        This creates a process when command is issued to execute the code. We execute or run the process. We get some results.
      • In Windows, a.exe or PESU.
      • In Linux, ./aout or ./PESU.
  • For interested students:
    • The following options of gcc are a good choice for finding problems in C and C++ programs.
      • gcc -ansi -pedantic -Wall -W -Wconversion -Wshadow -Wcast-qual -Wwrite-strings

Lecture #4: Program Structure, Characteristics, Errors

  • Characteristics of a C Program

    • Case sensitive.
    • Free format source code concept is followed.
    • Has a well-defined entry point, main().
    • Uses pre-processor directives starting with # (e.g., #include <stdio.h>).
    • main function returns 0 on success and non-zero on failure, by convention.
    • Statements end in a semicolon ;.
  • Program structure

    • Documentation Section:

      • Optional but recommended for providing code information via comments.
        • Single-line comments // comment.
        • Multi-line/block comments /* comment */.
    • Link Section:

      • Includes system library functions using #include directives.
      • Includes header files to execute C program.
    • Definition Section:

      • Optional section with definitions of functions used.
    • Global Declaration Section:

      • Optional section containing global variable declarations and function declarations (prototypes).
      • Contains global variable declaration and function declaration(no body, only prototype/signature).
    • Main function Section:

      • Main function is mandatory Section.
      • the declaration part and the executable part.
    • Contains declaration of variables and statements in executable part

    • The program execution begins at the opening brace and ends at the closing brace.

    • All statements in the declaration and executable part end with a semicolon.

      • Sub program section:
        • Optional section and contains user defined functions.
  • Return Value in main()

    • Indicates successful or unsuccessful execution (0 for success).
    • Use echo %ERRORLEVEL% (Windows) or echo $? (Linux) to check the return value.
  • Compilation using different C Standards
    * STDC_VERSION: A macro defined in stdio.h

  • Preprocessing and Compilation using C89: gcc –std=c89 -c first.c - results in Compile time Error

  • Preprocessing and Compilation using C99: gcc –std=c99 -c first.c

  • STDC_VERSION is a macro defined in stdio.h. To understand better, use codes using –E option of GCC.. Output: C standard is 199901
    Linked remains the same: gcc first.o

  • Preprocessing and Compilation using C11: gcc –std=c11 -c first.c Output: C standard is 201112 Linking can remain the same.

    • C89 standard does not have the
      STDC_VERSION
      macro, while the other standards do.
  • Errors in C Code

    • Error: A mistake or illegal operation that results in abnormal program behavior or prevents compilation and execution.

    • Compile time Error

      • Deviation from the rules of the Language or violating the rules of the language results in compile time Error.
      • Object file(.o file) will not be created. Hence linking is not possible.
        Whenever the programmer does not follow the syntax of any programming language, then the compiler will throw the Syntax Error which are also compile time errors. Syntax Errors are easy to figure out because the compiler highlights the line of code that caused the error.
      • Due to Syntax of the language .e.g.,Missing semicolon.
    • Link time Error

      • Errors encountered when the executable file of the code cannot be generated even though the code gets compiled successfully.
      • During linking, definition of Printf is not available in the included file. Hence Link time Error. No loadable object will be created due to this error. This Error is generated when a different object file is unable to link with the main object file
        Examples. A misspelt function name.
        *Mismatch between Function call and function definitions.
    • Run time Error

      • Errors that occur during program execution after successful compilation and linking.

        • Generally occurs due to some illegal operation performed in the program.
          Generally occurs due to some illegal operation performed in the program. Examples of some illegal operations that may produce runtime errors are: Dividing a number by zero, trying to open a file which is not created and lack of free memory space
      • Due to an error during the run (ex: dividing by zero
        printf("%d",12/0);

      • When the code is compiled, object file(.o file) will be created. Then during linking, executable will be created

    • Logical Error:

      • Logical error occurs when the code runs completely but the expected output is not same as the actual output.Coding Example_6:
      • The output generated deviates from the expected output due to flaws in judgment of the student in implementation.

Coding Example_6:

include #include int main () { /By Mistake entered 21 instead of 2 */ printf("%d",12/21); return 0; }

  • Warnings in C:
    • Diagnostic messages reporting risky constructions that may lead to errors or crashes.
    • ‘-Wall’ compiler option is essential for catching common errors.
    • Enabling warnings is crucial to avoid potential issues.
    • All arguments in printf and scanf families not matching the format string which is a common programmer mistake.
  • Error vs warning :
    • Errors prevent compilation, while warnings indicate potential issues but allow compilation to proceed.
    • GCC (-Wall) can report common programming mistakes by default. C and C++ compilers are notorious for making such mistakes.
    • Enabling Warnings : GCC use options like -Wall, -Wpedantic, -Wextra.
      *forgetting to initialise a variable
      *forgetting to return a value from a function
  • The compilation using –Wall creates an object file. But fails to execute at the runtime.