[C Language] Goto, Preprocessor Directives, Structures, and Unions
C language
1. goto
It is used to immediately jump to a specified label within the program.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <stdio.h> int main() { int num = 0; printf("Enter a positive number: "); scanf("%d", &num); if (num <= 0) { goto error; } printf("You entered: %d\n", num); return 0; error: printf("Error: The number is not positive.\n"); return 1; }
2. ifdef & endif
#ifdef
and#endif
are preprocessor directives and in C.1 2 3 4 5 6 7 8 9 10 11 12 13 14
#define DEBUG #ifdef DEBUG #include <stdio.h> #endif int main() { #ifdef DEBUG printf("Debug information\n"); #endif // Rest of the program return 0; }
If
DEBUG
is not defined (commented out or removed), the DEBUG macro would not be defined and theprintf
statement would not be compiled.
Struct
A structure in C is a user-defined data type that allows grouping different data types into a single unit. By using structures, collecting related data together into a group.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
#include <stdio.h> // Declaration of Student structure struct Student { char name[50]; int id; float averageScore; }; int main() { // Declaring and initializing a structure variable struct Student student1 = {"John Doe", 12345, 85.6}; // Accessing and printing structure members printf("Name: %s\n", student1.name); printf("ID: %d\n", student1.id); printf("Average Score: %.2f\n", student1.averageScore); return 0; }
Union
It is a user-defined data type that allows multiple members to
share
the same memory location.1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
union myUnion { int integer; float decimal; char character; }; union myUnion u; u.integer = 5; printf("%d\n", u.integer); // Outputs 5 u.decimal = 3.14; printf("%f\n", u.decimal); // Outputs 3.14 // Accessing u.integer at this point may produce an unexpected value u.character = 'A'; printf("%c\n", u.character); // Outputs 'A' // Accessing u.integer or u.decimal at this point may produce unexpected values
This post is licensed under CC BY 4.0 by the author.