Overview of C Programming
Open in the Padhaiko app2.1 Introduction to C programming
C is a general-purpose, procedural, structured, and middle-level programming language. It combines the expressive control structures and portability of high-level languages (functions, loops, structured data types) with low-level hardware capabilities (direct memory addressing via pointers, bitwise manipulation, and predictable byte-level layout).
Because C provides a thin abstraction over machine instructions without hidden runtime overhead, it remains the foundational language for operating systems, embedded firmware, device drivers, compilers, and high-performance libraries.
2.2 History and importance of C
C evolved through a clear lineage of systems languages at Bell Laboratories:
| Year | Language / Standard | Creator / Body | Key Milestone |
|---|---|---|---|
| 1960 | ALGOL 60 | International Committee | Introduced block structure and structured programming concepts |
| 1967 | BCPL | Martin Richards | Typeless systems language used for writing compilers |
| 1970 | B | Ken Thompson | Stripped-down successor to BCPL for early UNIX on PDP-7 |
| 1972 | Traditional C | Dennis Ritchie (Bell Labs) | Added data types (char, int, float) and structures to rewrite UNIX in C on PDP-11 |
| 1978 | K&R C | Brian Kernighan & Dennis Ritchie | The C Programming Language served as the informal standard |
| 1989 / 1990 | ANSI C / ISO C (C89 / C90) | ANSI X3J11 / ISO | First formal portable standard introducing function prototypes and void |
| 1999 / 2011 / 2017 | C99 / C11 / C17 | ISO/IEC JTC1/SC22/WG14 | Added // comments, long long int, <stdbool.h>, multithreading, and safety fixes |
Why C Remains Important:
- System-Level Power: Operating system kernels (Linux, Windows core subsystems, macOS Darwin) and embedded microcontrollers are written predominantly in C.
- Speed and Efficiency: Compiled directly to native machine code with minimal runtime footprint.
- Portability: Standard C code compiles with few or no modifications across diverse hardware architectures.
- Rich Standard Library and Foundation: Forms the syntactic and conceptual ancestor of C++, Java, C#, JavaScript, and PHP.
2.3 C headers and library functions
Rather than bloating the core language with built-in I/O or math keywords, C delegates these capabilities to library functions organized by header files (.h). A header file contains function declarations (prototypes), macro constants, and type definitions so the compiler can verify argument and return types before the linker attaches the compiled library code.
| Header File | Purpose | Common Library Functions / Macros |
|---|---|---|
<stdio.h> | Standard Input/Output | printf(), scanf(), getchar(), putchar(), fopen(), fclose(), EOF |
<math.h> | Mathematical Functions | sqrt(), pow(), sin(), cos(), fabs(), ceil(), floor() |
<string.h> | String & Memory Operations | strlen(), strcpy(), strcat(), strcmp(), memcpy() |
<stdlib.h> | General Utilities & Dynamic Memory | malloc(), calloc(), free(), exit(), atoi(), rand(), abs() |
<ctype.h> | Character Testing & Conversion | isalpha(), isdigit(), isspace(), toupper(), tolower() |
<limits.h> | Integer Type Limits | INT_MAX, INT_MIN, CHAR_BIT, UINT_MAX |
2.4 Basic structure of a C program
Every standalone C program follows a standard structural layout consisting of six well-defined sections:
| Section | Role | Mandatory? |
|---|---|---|
| 1. Documentation Section | Comments (/* ... */ or //) describing author, date, and purpose | Optional (strongly recommended) |
| 2. Link Section | #include directives bringing in header declarations | Almost always needed (e.g., <stdio.h>) |
| 3. Definition Section | #define symbolic constants and macros | Optional |
| 4. Global Declaration Section | Global variables and user-defined function prototypes | Optional |
5. main() Function Section | Entry point of program execution (int main(void)); contains declaration and executable parts | Mandatory (exactly one main per program) |
| 6. Subprogram Section | User-defined function definitions called from main() or other functions | Optional |
/* Program: Calculate area and circumference of a circle */
#include <stdio.h> /* Link section */
#define PI 3.14159 /* Definition section */
double calc_area(double r); /* Global function prototype */
int main(void) { /* main() entry point */
double radius = 5.0; /* Local variable declaration */
double area = calc_area(radius); /* Executable statement */
printf("Area = %.2f\n", area);
return 0; /* Exit status 0 = success */
}
double calc_area(double r) { /* Subprogram definition */
return PI * r * r;
}2.5 Preprocessor directives
The C Preprocessor (cpp) runs automatically before actual compilation. Every preprocessor directive begins with # at the start of a line and does not end with a semicolon (;).
Common C Preprocessor Directives
- File Inclusion (
#include): Inserts the full text of a header file into the source file before compilation.#include <stdio.h>searches standard system include directories.#include "myheader.h"searches the current project directory first, then system directories.
- Macro Substitution (
#defineand#undef):- Object-like macro:
#define MAX 100replaces every occurrence of tokenMAXwith100. - Function-like macro:
#define SQR(x) ((x) * (x))substitutes inline expressions textually. Parentheses around parameters and the entire macro prevent operator-precedence surprises.
- Object-like macro:
- Conditional Compilation (
#ifdef,#ifndef,#if,#else,#endif): Includes or skips blocks of code at compile time (used heavily in header guards and cross-platform builds).
2.6 Tokens in C (Character set, keywords and identifiers)
A token is the smallest individual lexical unit recognized by the C compiler. C source code is built from characters in the C Character Set:
- Letters:
A–Z,a–z(case-sensitive) - Digits:
0–9 - Special characters:
+ - * / % = & | ^ ~ ! < > ( ) { } [ ] ; : , . # _ " ' ? \ - Whitespace: spaces, tabs (
\t), newlines (\n) used to separate tokens
| Token Type | Meaning | Examples |
|---|---|---|
| Keywords | Reserved words with fixed meaning in C (32 in ANSI C89) | int, float, if, else, for, while, return, struct, sizeof |
| Identifiers | User-defined names for variables, functions, arrays, and structs | sum, student_age, _count, calcArea |
| Constants | Fixed literal values that do not change during execution | 42, 3.14f, 'A', "Institute of Engineering" |
| String Literals | Sequence of characters enclosed in double quotes ending with '\0' | "Hello", "ENCT 101" |
| Operators | Symbols specifying arithmetic, logical, or bitwise actions | +, -, *, /, &&, ==, ++ |
| Punctuators / Separators | Structural delimiters | ;, ,, (, ), {, } |
Rules for Valid C Identifiers:
- Must begin with a letter (
A–Z,a–z) or an underscore (_). - Subsequent characters may be letters, digits (
0–9), or underscores (_). - Cannot be a reserved C keyword (e.g.,
int,float,switch). - Cannot contain spaces, hyphens (
-), or special symbols (@,#,%). - Identifiers are case-sensitive (
total,Total, andTOTALare three distinct names).
2.7 Type casting (Implicit and explicit)
Type casting (type conversion) converts a value from one data type to another so operations match compatible representations.
| Aspect | Implicit Type Conversion (Type Promotion) | Explicit Type Casting |
|---|---|---|
| Who Performs It | Performed automatically by the C compiler | Written explicitly by the programmer using (type) expression |
| Direction | Usually widening (lower rank promoted to higher rank along char -> int -> long -> float -> double) to avoid data loss | Can widen or narrow intentionally (e.g., (int) 3.9 truncates fractional part to 3) |
| Syntax | double d = 5 + 2.5; (5 promoted to 5.0) | double avg = (double) sum / count; |
| Common Pitfall | Integer division 5 / 2 yields 2, even if assigned to a float (float f = 5 / 2; stores 2.0) | Casting after division (double)(5 / 2) is too late; it casts 2 to 2.0 |
Usual Arithmetic Conversion Hierarchy: When a binary operator mixes types, the smaller type is promoted upward before the operation: short / char -> int -> unsigned int -> long -> float -> double -> long double.
2.8 Data types, variables and constants
A variable is a named storage location in memory whose value can change during program execution, while a constant is an unmodifiable value. Every variable in C must be declared with a data type before use so the compiler knows how many bytes to allocate and how to interpret the stored bits.
| Data Type | Size (Bytes) | Format Specifier | Typical Value Range | Purpose |
|---|---|---|---|---|
char | 1 | %c | -128 to 127 (signed) or 0 to 255 (unsigned) | Single ASCII character or small byte |
short int | 2 | %hd | -32,768 to 32,767 | Small integers |
int | 4 | %d | -2,147,483,648 to 2,147,483,647 | Standard signed integers |
unsigned int | 4 | %u | 0 to 4,294,967,295 | Non-negative integers |
long long int | 8 | %lld | -9.22e18 to 9.22e18 | Very large integers |
float | 4 | %f | ~1.2e-38 to 3.4e38 (6–7 digits precision) | Single-precision floating-point |
double | 8 | %lf | ~2.3e-308 to 1.7e308 (15 digits precision) | Double-precision floating-point |
void | — | — | No values | Empty type (functions returning nothing, generic pointers) |
Declaring Variables and Constants:
- Variable declaration & initialization:
int count = 0; float rate = 9.5f; - Constants using
const:const double TAX_RATE = 0.13;(enforced read-only by the compiler with type checking). - Symbolic constants using
#define:#define MAX_STUDENTS 60(textual substitution before compilation, zero memory allocation). - Literal constants: Integer (
42,075octal,0x2Ahexadecimal), floating-point (3.14,1.5e-3), character ('A','\n'), and string ("Hello").
2.9 Compiler and IDE for C programming
Writing and running C code requires a compiler (to translate source files into executables) and optionally an IDE (Integrated Development Environment) that combines an editor, compiler invocation, and debugger.
| Tool | Category | Platform | Key Features |
|---|---|---|---|
GCC (gcc) | Compiler | Linux, macOS, Windows (MinGW) | Open-source GNU Compiler Collection; standard CLI compilation (gcc prog.c -o prog -Wall) |
Clang (clang) | Compiler | Linux, macOS, Windows | Fast compilation and clear diagnostic messages |
MSVC (cl) | Compiler | Windows | Microsoft Visual C++ toolchain |
| VS Code | Lightweight Editor / IDE | Cross-platform | Syntax highlighting, integrated terminal, debugging with GDB/LLDB |
| Code::Blocks / Dev-C++ | Beginner C/C++ IDE | Windows / Linux | Pre-packaged GUI with bundled MinGW GCC compiler |
| Turbo C / C++ | Legacy 16-bit IDE | DOS / DOSBox | Historical textbook tool (non-standard <conio.h>, 16-bit int); avoid for modern C11/C17 work |
Worked Examples
1
Predict the exact output of the following C program that demonstrates integer division, implicit promotion, and explicit type casting:
#include <stdio.h>
int main(void) {
int a = 17, b = 4;
double r1 = (a + b) / 2;
double r2 = (double)(a + b) / 2;
double r3 = (double)((a + b) / 2);
printf("r1=%.2f r2=%.2f r3=%.2f\n", r1, r2, r3);
return 0;
}Evaluating r1 = (a + b) / 2;: Both (a + b) = 21 and 2 are of type int. C performs integer division, discarding the remainder: 21 / 2 evaluates to integer 10. Only during assignment to double r1 is 10 implicitly converted to 10.00.
Evaluating r2 = (double)(a + b) / 2;: (a + b) evaluates to 21, which is explicitly cast to 21.0 (double). Because one operand of / is now double, C implicitly promotes 2 to 2.0, producing 21.0 / 2.0 = 10.50.
Evaluating r3 = (double)((a + b) / 2);: The inner expression (a + b) / 2 executes first as integer division (21 / 2 = 10), and only then is 10 cast to 10.00.
Output:
r1=10.00 r2=10.50 r3=10.002
Classify each of the following candidate identifiers in C as valid or invalid. For every invalid identifier, state the exact rule violated: totalMarks, 2nd_value, _buffer, float, student-id, MAX_SIZE, roll no, int_1.
Checking Each Candidate Against C Identifier Rules:
totalMarks: Starts with a letter and uses only letters -> Valid.2nd_value: Begins with digit2-> Invalid (identifiers cannot start with a digit)._buffer: Begins with underscore_followed by letters -> Valid.float: Matches a reserved C keyword -> Invalid (keywords cannot be used as identifiers).student-id: Contains a hyphen-(subtraction operator) -> Invalid (only letters, digits, and_are allowed).MAX_SIZE: Letters and underscore -> Valid.roll no: Contains a whitespace space -> Invalid (whitespace is a token separator, not permitted inside an identifier).int_1: Starts with a letter;intis only a prefix, not the standalone keywordint-> Valid.
- Valid:
totalMarks,_buffer,MAX_SIZE,int_1 - Invalid:
2nd_value(starts with digit),float(reserved keyword),student-id(contains-),roll no(contains space).
3
Explain why parenthesizing #define macro parameters matters by tracing the output of this program:
#include <stdio.h>
#define BAD_MUL(a, b) a * b
#define GOOD_MUL(a, b) ((a) * (b))
int main(void) {
int x = BAD_MUL(3 + 1, 10 + 2);
int y = GOOD_MUL(3 + 1, 10 + 2);
printf("x=%d y=%d\n", x, y);
return 0;
}Expanding BAD_MUL(3 + 1, 10 + 2): The preprocessor performs raw text replacement before compilation: int x = 3 + 1 * 10 + 2; Because * has higher precedence than +, this evaluates as 3 + (1 * 10) + 2 = 3 + 10 + 2 = 15 (note: not (3 + 1) * (10 + 2)!).
Expanding GOOD_MUL(3 + 1, 10 + 2): With parentheses around every parameter and the macro body: int y = ((3 + 1) * (10 + 2)); This evaluates as 4 * 12 = 48.
Output: x=15 y=48. Always wrap macro arguments and the macro result in parentheses because #define performs textual substitution before operator precedence rules are applied.
Exercises
Exercises — Overview of C Programming
Why is C called a "middle-level" structured programming language? Mention four key historical milestones in its evolution from ALGOL/BCPL to ANSI C.
Why C is Middle-Level: C bridges high-level structured programming (portable control flow, functions, typed variables, standard libraries) and low-level machine programming (pointers for direct memory access, bitwise operations, compact machine code).
Four Historical Milestones:
- 1967 (BCPL by Martin Richards): Typeless systems language influencing B.
- 1970 (B by Ken Thompson): Early UNIX systems language at Bell Labs.
- 1972 (C by Dennis Ritchie): Added data types and structures to rewrite the UNIX kernel.
- 1989 (ANSI C / C89): Standardized the language formally across compilers and platforms.
C is called middle-level because it pairs high-level structured abstractions with low-level pointer and bit-level control. Key milestones: BCPL (1967) -> B (1970) -> Dennis Ritchie's typed C (1972) -> ANSI C standard (1989).
Describe the six basic sections of a C program and explain the specific roles of <stdio.h> and return 0; inside main().
Six Sections: Documentation (comments), Link (#include), Definition (#define), Global Declaration (global variables and function prototypes), main() Function (declarations and executable statements), and Subprogram Section (user-defined functions).
Roles of <stdio.h> and return 0;:
#include <stdio.h>supplies prototypes for standard I/O functions such asprintf()andscanf()so the compiler checks argument types and return values.return 0;inint main(void)returns exit status0to the operating system, signaling normal error-free termination.
A C program comprises Documentation, Link, Definition, Global Declaration, main(), and Subprogram sections. <stdio.h> provides declarations for standard I/O functions (printf, scanf), while return 0; reports successful program termination to the OS.
What is a token in C? List all six types of C tokens with two examples of each, and state the rules for forming a valid identifier.
Definition and Six Token Categories: A token is the smallest meaningful unit of a C program recognized by the lexical analyzer:
- Keywords:
int,return - Identifiers:
total,calc_sum - Constants:
25,'A' - String Literals:
"Nepal","123" - Operators:
+,&& - Punctuators:
;,{
Rules for Valid Identifiers:
- Start with an alphabet (
A–Z,a–z) or underscore (_). - Contain only letters, digits (
0–9), and underscores. - Cannot be a C keyword; no spaces or punctuation; case-sensitive.
Tokens are the six atomic building blocks of C code (keywords, identifiers, constants, string literals, operators, punctuators). Valid identifiers start with a letter or _, contain only letters/digits/_, are case-sensitive, and cannot match keywords.
Explain the difference between implicit type conversion and explicit type casting. Given int a = 7, b = 2;, what values are stored in float x = a / b; and float y = (float)a / b;?
Implicit vs. Explicit Conversion:
- Implicit conversion is performed automatically by the compiler when mixed types appear in an expression (promoting smaller types to larger types).
- Explicit casting uses the
(type)operator written by the programmer to force conversion at a chosen point.
Evaluating x and y:
- In
float x = a / b;, bothaandbareint, so integer division7 / 2gives3, which is then implicitly promoted to3.0when stored inx. - In
float y = (float)a / b;,(float)aconverts7to7.0f;bis implicitly promoted to2.0f, giving7.0 / 2.0 = 3.5.
Implicit conversion is automatic type promotion by the compiler, whereas explicit casting uses (type) expr. For a = 7, b = 2: x stores 3.0 (integer division before assignment) and y stores 3.5 (float division after explicit cast).
Compare #define symbolic constants with const variables in C across at least four criteria (processing stage, type safety, memory usage, and scope).
Comparison Criteria:
- Processing Stage:
#defineis handled textually by the preprocessor before compilation;constis checked by the compiler during compilation. - Type Safety:
#definehas no data type and no compiler type checking;constrequires an explicit type (const int N = 10;). - Memory & Debugging:
#definesubstitutes literals directly (no memory address, invisible to debuggers);constvariables occupy typed storage (unless optimized out) and have symbol names in debuggers. - Scope Rules:
#defineapplies globally from its line to the end of the file (unless#undefined);constobeys normal C block/file scope rules.
#define performs untyped preprocessor text substitution globally without allocating a typed variable, whereas const defines a type-checked, scoped read-only variable handled by the compiler.