Welcome to our deep dive into the world of C Programming! Today, we're going to explore the #else directive, a powerful tool that can help you make decisions in your code.
#else Directive? 📝In C programming, the #else directive is used in conjunction with #if and #ifdef to create multi-branch conditionals. When followed by a statement or block, #else is executed if the condition in the preceding #if or #ifdef is not satisfied.
Let's start with a simple example to understand the concept:
#include <stdio.h>
int main() {
int age = 18;
#if age >= 18
printf("You are eligible to vote.\n");
#else
printf("You are not eligible to vote.\n");
#endif
return 0;
}In this example, we have an age variable set to 18. The #if statement checks if the age is greater than or equal to 18. If the condition is true, the message "You are eligible to vote." is printed. If the condition is false (for example, if age was set to 17), the message "You are not eligible to vote." is printed instead.
Now, let's take it a step further:
#include <stdio.h>
#define MIN_AGE_TO_VOTE 18
#define MIN_AGE_TO_DRIVE 16
int main() {
int age = 18;
char license;
#if age >= MIN_AGE_TO_VOTE
printf("You are eligible to vote.\n");
#if age >= MIN_AGE_TO_DRIVE
license = 'Y';
printf("You are also eligible to drive.\n");
#else
license = 'N';
printf("You are eligible to vote, but not to drive.\n");
#endif
#else
printf("You are not eligible to vote or drive.\n");
#endif
printf("Your driving license status is: %c\n", license);
return 0;
}In this example, we have two minimum ages defined: 18 for voting and 16 for driving. The code first checks if the age is eligible for voting, then checks if it's eligible for driving. If the age is eligible for both, it sets the license variable to 'Y'. If the age is eligible for voting but not for driving, it sets license to 'N'.
Which statement is executed if the condition in an `#if` statement is not satisfied, but there is an `#else` statement following it?
Remember, the #else directive can help you create more complex conditionals, making your code more flexible and powerful. Happy coding! 🎉