C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972.
It is a very popular language, despite being old. The main reason for its popularity is because it is a fundamental language in the field of computer science.
C is strongly associated with UNIX, as it was developed to write the UNIX operating system.
Variables & Constants in C
Variables
Variables in C are named memory locations used to store data that can vary during the execution of the program. They are defined with a specific data type that determines the size and type of data they can hold. Here are the key points about variables:
Declaration:
Before using a variable in C, you must declare it with a specific data type.
Initialization:
Variables can optionally be initialized at the time of declaration.
Assignment:
Once declared, variables can be assigned new values using the assignment operator (=).
Scope:
Variables have a scope that determines where in the program they can be accessed.
Constants
Constants in C are values that do not change during the execution of a program. They can be of any data type and are declared using the const keyword. Constants provide a way to make code more readable and maintainable by giving meaningful names to values that remain fixed.
Declaration:
Constants are declared using the const keyword followed by the data type and the constant name.
Usage:
Once declared, constants cannot be modified throughout the program execution:
Advantages:
Constants improve code readability by providing meaningful names to values that should not change. They also help prevent inadvertent modification of values.
Operators & Control flow in C
Operators
Operators in C can be categorized into several types based on their functionality:
Arithmetic Operators:
Used for performing mathematical calculations:
Addition (+), Subtraction (-), Multiplication (*), Division (/), Modulus (%)
Relational Operators:
Used for comparing values:
Equal to (==), Not equal to (!=), Greater than (>), Less than (<), Greater than or equal to (>=), Less than or equal to (<=)
Logical Operators:
Used to combine multiple conditions:
Logical AND (&&), Logical OR (||), Logical NOT (!)
Assignment Operators:
Used to assign values to variables:
Assignment (=), Addition assignment (+=), Subtraction assignment (-=), Multiplication assignment (*=), Division assignment (/=), Modulus assignment (%=)
Increment and Decrement Operators:
Used to increase or decrease the value of a variable:
Increment (++), Decrement (--)
Bitwise Operators:
Used for manipulation of bits in integers:
Bitwise AND (&), Bitwise OR (|), Bitwise XOR (^), Bitwise NOT (~), Left shift (<<), Right shift (>>)
Ternary Operator:
Conditional operator for decision making:
condition ? expression1 : expression2
Control Flow Statements
Control flow statements dictate the order in which statements in your code are executed based on certain conditions or loops. Key control flow statements in C include:
Conditional Statements:
if statement:
if-else statement:
else-if ladder:
Switch Statement:
Used to select one of many code blocks to be executed:
Loops:
while loop:
Executes a block of code as long as a specified condition is true.
do-while loop:
Similar to the while loop but guarantees that the block of code is executed at least once before checking the condition.
for loop:
Executes a block of code a specified number of times.
File handling & Error Handling
File Handling in C
File handling in C involves operations to read from and write to files. This process typically involves the following steps:
File Pointer:
In C, a file is accessed using a file pointer (FILE *). This pointer maintains information about the file being accessed.
Opening a File:
Before reading from or writing to a file, you need to open it using the fopen() function:
Reading from a File:
You can use functions like fscanf() or fgets() to read data from a file:
Writing to a File:
Use functions like fprintf() or fputs() to write data to a file:
Closing a File:
Always close the file using fclose() once you’re done with it to free up resources:
Error Handling:
Check the return value of fopen() to ensure the file was opened successfully. If fp is NULL, an error occurred.
Error Handling in C
Error handling in C involves managing unexpected situations or errors that may occur during program execution. Common techniques include:
Return Values:
Functions in C often return values indicating success or failure (0 for success, -1 or NULL for failure). Always check return values for errors, especially when dealing with file operations (fopen(), fclose(), etc.).
Error Codes:
Standard library functions like errno and perror() can help diagnose errors:
Custom Error Handling:
Use conditional statements (if, else, switch) to handle specific errors:
Error Reporting:
Print informative error messages to stderr (fprintf(stderr, ...)):
Cleanup:
Always clean up resources (like closing files with fclose()) before exiting due to an error to prevent resource leaks.
Data types in C
Basic Data Types
Integer Types:
char:
Typically 1 byte in size. Used for storing characters or small integers. Range depends on whether it's signed or unsigned.
char or signed char: -128 to 127 or 0 to 255 (if unsigned)
int:
Typically 4 bytes in size on modern systems. Used for storing integers.
int: -2147483648 to 2147483647
short:
Typically 2 bytes in size. Used for smaller integers.
short int or short: -32768 to 32767
long:
Typically 4 bytes in size. Used for larger integers.
long int or long: -2147483648 to 2147483647
long long:
Typically 8 bytes in size. Used for very large integers.
long long int or long long: -9223372036854775808 to 9223372036854775807
Floating-Point Types:
float:
Typically 4 bytes in size. Used for single-precision floating-point numbers.
float: ±1.17549435 × 10^-38 to ±3.40282347 × 10^38
double:
Typically 8 bytes in size. Used for double-precision floating-point numbers.
double: ±2.2250738585072014 × 10^-308 to ±1.7976931348623157 × 10^308
long double:
Size varies (usually 10 or 12 bytes). Used for extended-precision floating-point numbers.
Void Type:
void: Represents the absence of type. Used in function returns and pointers.
Derived Data Types
Array Types:
Collection of elements of the same data type.
eg. int arr[5]; // Array of 5 integers
Pointer Types:
Stores memory addresses of variables.
eg. int *ptr; // Pointer to an integer
Structure Types:
Groups different data types together under a single name.
eg. struct Person {
char name[50];
int age;
};
Union Tesyp:
Similar to structures but share the same memory location for all members.
eg. union Data {
int i;
float f;
char str[20];
};