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! 📝
#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.
The syntax for the #elif directive is as follows:
#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
#endifLet's dive into a few examples to better understand the #elif directive.
Example 1 - Checking Age Group
#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
#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;
}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! 🎯