C Programming: Understanding the #elif Directive 🎯

beginner
21 min

C Programming: Understanding the #elif Directive 🎯

Welcome to this comprehensive guide on the #elif directive in C programming! In this lesson, we'll explore the purpose, syntax, and practical uses of this powerful tool. Let's embark on a journey to learn together! 📝

What is the #elif Directive? 💡

The #elif (short for "else if") directive is a conditional preprocessor statement in C programming that checks whether a specific condition is true. It is a part of the multi-condition checking process, used when more than one condition needs to be checked sequentially.

Syntax 📝

The syntax for the #elif directive is as follows:

c
#if (condition1) // Code block if condition1 is true #elif (condition2) // Code block if condition1 is false and condition2 is true #elif (condition3) // Code block if condition1 and condition2 are false, and condition3 is true ... #else // Default code block if all conditions are false #endif

Practical Examples 💡

Let's dive into a few examples to better understand the #elif directive.

Example 1 - Checking Age Group

c
#include <stdio.h> int main() { int age; printf("Enter your age: "); scanf("%d", &age); // Check if the age is within a certain range #if (age >= 0 && age <= 2) printf("You are an infant.\n"); #elif (age >= 3 && age <= 12) printf("You are a child.\n"); #elif (age >= 13 && age <= 19) printf("You are a teenager.\n"); #elif (age >= 20 && age <= 64) printf("You are an adult.\n"); #elif (age >= 65) printf("You are a senior citizen.\n"); #else printf("Invalid age.\n"); return 0; }

Example 2 - Checking the Status of a File

c
#include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <sys/stat.h> int main() { int fileStatus; // Check if the file "example.txt" exists and is a regular file #if (access("example.txt", F_OK) == 0 && (fileStatus = open("example.txt", O_RDONLY)) != -1) { printf("The file 'example.txt' exists and is a regular file.\n"); close(fileStatus); } #elif (access("example.txt", F_OK) == -1) { printf("The file 'example.txt' does not exist.\n"); } #elif (access("example.txt", F_OK) == 0 && (fileStatus = open("example.txt", O_RDONLY)) == -1) { printf("The file 'example.txt' exists but is not a regular file.\n"); } #else printf("An error occurred while checking the file.\n"); return 0; }

Quiz Time! 💡

Quick Quiz
Question 1 of 1

What does the `#elif` directive do in C programming?

Happy coding, and we hope this guide has helped you understand the #elif directive in C programming! 🎯