c
exercises
exercises.c🔧c
/*
* ============================================================================
* COMPILATION PROCESS - EXERCISES
* ============================================================================
* Complete the exercises to understand C compilation stages.
*
* Instructions:
* 1. Read each exercise carefully
* 2. Complete the TODO sections
* 3. Follow the compilation instructions in each exercise
* 4. Compare your output with expected results
* ============================================================================
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*
* ============================================================================
* EXERCISE 1: Basic Macros
* ============================================================================
* Difficulty: Easy
*
* Task: Define the following macros and use them in the function:
* 1. PROGRAM_VERSION - string "1.0.0"
* 2. MAX_SIZE - integer 100
* 3. DOUBLE(x) - macro that doubles a number
* 4. TRIPLE(x) - macro that triples a number
*
* Expected Output:
* Version: 1.0.0
* Max Size: 100
* Double of 5: 10
* Triple of 5: 15
*/
// TODO: Define PROGRAM_VERSION
// TODO: Define MAX_SIZE
// TODO: Define DOUBLE(x) macro
// TODO: Define TRIPLE(x) macro
void exercise_1() {
printf("\n=== Exercise 1: Basic Macros ===\n");
// TODO: Print PROGRAM_VERSION
// TODO: Print MAX_SIZE
// TODO: Use DOUBLE and TRIPLE with the value 5
}
/*
* ============================================================================
* EXERCISE 2: Conditional Compilation
* ============================================================================
* Difficulty: Easy
*
* Task: Use conditional compilation to:
* 1. Define a DEBUG flag at the top
* 2. Print debug messages only when DEBUG is defined
* 3. Print release messages when DEBUG is not defined
*
* Expected Output (with DEBUG defined):
* DEBUG MODE ACTIVE
* Debug: Variable x = 42
* Debug: Processing complete
*
* Expected Output (without DEBUG):
* RELEASE MODE
*/
// TODO: Define or comment out DEBUG flag
// #define DEBUG
void exercise_2() {
printf("\n=== Exercise 2: Conditional Compilation ===\n");
int x = 42;
// TODO: Use #ifdef DEBUG to conditionally print debug info
// If DEBUG is defined:
// - Print "DEBUG MODE ACTIVE"
// - Print "Debug: Variable x = " followed by x value
// - Print "Debug: Processing complete"
// If DEBUG is not defined:
// - Print "RELEASE MODE"
}
/*
* ============================================================================
* EXERCISE 3: Predefined Macros
* ============================================================================
* Difficulty: Easy
*
* Task: Create a logging macro that uses predefined macros to show:
* - File name
* - Line number
* - Function name
* - The log message
*
* Expected Output:
* [exercises.c:123:exercise_3] This is a log message
* [exercises.c:124:exercise_3] Another log entry
*/
// TODO: Define a LOG(msg) macro that prints:
// [__FILE__:__LINE__:__func__] msg
void exercise_3() {
printf("\n=== Exercise 3: Predefined Macros ===\n");
// TODO: Use your LOG macro to print two messages
// Also print compilation info:
printf("\nCompilation Information:\n");
// TODO: Print the date this was compiled
// TODO: Print the time this was compiled
}
/*
* ============================================================================
* EXERCISE 4: Safe Macros
* ============================================================================
* Difficulty: Medium
*
* Task:
* 1. Write a BROKEN_SQUARE(x) macro that has a bug: x * x
* 2. Write a SAFE_SQUARE(x) macro with parentheses: ((x) * (x))
* 3. Demonstrate why parentheses matter with SQUARE(2+3)
*
* Expected Output:
* BROKEN_SQUARE(5) = 25
* SAFE_SQUARE(5) = 25
* BROKEN_SQUARE(2+3) = 11 (BUG! Should be 25)
* SAFE_SQUARE(2+3) = 25 (Correct!)
*
* Explanation:
* BROKEN_SQUARE(2+3) expands to: 2+3 * 2+3 = 2+6+3 = 11
* SAFE_SQUARE(2+3) expands to: ((2+3) * (2+3)) = 5*5 = 25
*/
// TODO: Define BROKEN_SQUARE(x) without proper parentheses
// TODO: Define SAFE_SQUARE(x) with proper parentheses
void exercise_4() {
printf("\n=== Exercise 4: Safe Macros ===\n");
// TODO: Demonstrate both macros with value 5
// TODO: Demonstrate the bug with 2+3
// TODO: Print the explanation
}
/*
* ============================================================================
* EXERCISE 5: Stringification and Concatenation
* ============================================================================
* Difficulty: Medium
*
* Task:
* 1. Define STRINGIFY(x) macro using # operator
* 2. Define PASTE(a, b) macro using ## operator
* 3. Use them to create variable names and strings dynamically
*
* Expected Output:
* STRINGIFY(hello) = "hello"
* STRINGIFY(123) = "123"
* var_1 = 100
* var_2 = 200
* var_3 = 300
*/
// TODO: Define STRINGIFY(x) using # operator
// TODO: Define PASTE(a, b) using ## operator
void exercise_5() {
printf("\n=== Exercise 5: Stringification & Concatenation ===\n");
// TODO: Use STRINGIFY macro
// TODO: Create variables var_1, var_2, var_3 using PASTE
// TODO: Print all variables
}
/*
* ============================================================================
* EXERCISE 6: Include Guards Simulation
* ============================================================================
* Difficulty: Medium
*
* Task: Create a simulated header file section with include guards.
* Define a structure that would normally be in a header file.
*
* Structure: Rectangle
* - int width
* - int height
*
* Function: calculateArea (prototype only in "header", definition below)
*/
// ===== SIMULATED HEADER FILE START =====
// TODO: Add include guard (#ifndef RECTANGLE_H, #define RECTANGLE_H)
// TODO: Define Rectangle structure
// TODO: Add function prototype for calculateArea
// TODO: Close include guard (#endif)
// ===== SIMULATED HEADER FILE END =====
// TODO: Define calculateArea function here (implementation)
void exercise_6() {
printf("\n=== Exercise 6: Include Guards ===\n");
// TODO: Create a Rectangle and calculate its area
}
/*
* ============================================================================
* EXERCISE 7: Multi-line Macros
* ============================================================================
* Difficulty: Medium
*
* Task: Define a multi-line macro using backslash continuation:
* PRINT_ARRAY(arr, size) - prints all elements of an array
*
* Expected Output:
* Array contents: 1 2 3 4 5
*/
// TODO: Define PRINT_ARRAY(arr, size) macro using \ for continuation
// The macro should:
// 1. Print "Array contents: "
// 2. Loop through and print each element
void exercise_7() {
printf("\n=== Exercise 7: Multi-line Macros ===\n");
int arr[] = {1, 2, 3, 4, 5};
int size = 5;
// TODO: Use PRINT_ARRAY macro
}
/*
* ============================================================================
* EXERCISE 8: Compilation Commands Practice
* ============================================================================
* Difficulty: Easy (but requires terminal)
*
* Task: This exercise requires running commands in terminal.
* The function explains what to do, then you execute the commands.
*
* After completing, answer the questions in the comments below.
*/
void exercise_8() {
printf("\n=== Exercise 8: Compilation Commands ===\n");
printf("\nRun these commands in your terminal:\n\n");
printf("1. Generate preprocessed output:\n");
printf(" gcc -E exercises.c -o exercises.i\n");
printf(" wc -l exercises.i (count lines)\n\n");
printf("2. Generate assembly:\n");
printf(" gcc -S exercises.c -o exercises.s\n");
printf(" head -50 exercises.s (view first 50 lines)\n\n");
printf("3. Generate object file:\n");
printf(" gcc -c exercises.c -o exercises.o\n");
printf(" nm exercises.o (view symbol table)\n\n");
printf("4. Generate executable:\n");
printf(" gcc exercises.c -o exercises_exe\n");
printf(" file exercises_exe (view file type)\n\n");
printf("5. View shared libraries:\n");
printf(" ldd exercises_exe\n\n");
}
/*
* QUESTIONS (answer in comments after running commands):
*
* Q1: How many lines are in the preprocessed file (exercises.i)?
* A1: _______________
*
* Q2: What section (.text, .data, etc.) contains the main function in assembly?
* A2: _______________
*
* Q3: What symbol type (T, t, U, etc.) does 'main' have in the object file?
* A3: _______________
*
* Q4: What type of file is the executable (ELF, PE, Mach-O)?
* A4: _______________
*
* Q5: What C library is linked (libc.so.6, etc.)?
* A5: _______________
*/
/*
* ============================================================================
* EXERCISE 9: Platform-Specific Code
* ============================================================================
* Difficulty: Medium
*
* Task: Write platform-specific code that:
* 1. Detects the operating system
* 2. Prints the appropriate clear screen command
* 3. Prints the path separator used
*
* Expected Output (on Linux):
* Operating System: Linux
* Clear command: clear
* Path separator: /
*/
void exercise_9() {
printf("\n=== Exercise 9: Platform-Specific Code ===\n");
// TODO: Use preprocessor to detect OS and print information
// Check for: _WIN32, __linux__, __APPLE__
// Print: OS name, clear command, path separator
}
/*
* ============================================================================
* BONUS EXERCISE: Create Your Own Assert Macro
* ============================================================================
* Difficulty: Hard
*
* Task: Create an ASSERT(condition) macro that:
* 1. Checks if condition is false
* 2. If false, prints: "Assertion failed: [condition], file [file], line [line]"
* 3. If false, exits the program
*
* Expected Output:
* Test 1 passed
* Test 2 passed
* Assertion failed: (x > 100), file exercises.c, line XXX
*/
// TODO: Define ASSERT(condition) macro
void bonus_exercise() {
printf("\n=== BONUS: Custom Assert ===\n");
int x = 50;
// TODO: Use ASSERT to test conditions
// ASSERT(x > 0); // Should pass
// ASSERT(x < 100); // Should pass
// ASSERT(x > 100); // Should fail and exit
printf("All assertions passed!\n");
}
/*
* ============================================================================
* MAIN FUNCTION
* ============================================================================
*/
int main() {
printf("╔════════════════════════════════════════════════╗\n");
printf("║ COMPILATION PROCESS - EXERCISES ║\n");
printf("║ Complete each exercise below ║\n");
printf("╚════════════════════════════════════════════════╝\n");
// Uncomment each exercise as you complete it
// exercise_1();
// exercise_2();
// exercise_3();
// exercise_4();
// exercise_5();
// exercise_6();
// exercise_7();
// exercise_8();
// exercise_9();
// bonus_exercise();
printf("\n=== Uncomment exercises in main() to run them ===\n");
return 0;
}
/*
* ============================================================================
* ANSWER KEY
* ============================================================================
*
* Exercise 1:
* #define PROGRAM_VERSION "1.0.0"
* #define MAX_SIZE 100
* #define DOUBLE(x) ((x) * 2)
* #define TRIPLE(x) ((x) * 3)
*
* Exercise 3:
* #define LOG(msg) printf("[%s:%d:%s] %s\n", __FILE__, __LINE__, __func__, msg)
*
* Exercise 4:
* #define BROKEN_SQUARE(x) x * x
* #define SAFE_SQUARE(x) ((x) * (x))
*
* Exercise 5:
* #define STRINGIFY(x) #x
* #define PASTE(a, b) a##b
*
* BONUS (Assert):
* #define ASSERT(condition) \
* do { \
* if (!(condition)) { \
* printf("Assertion failed: (%s), file %s, line %d\n", \
* #condition, __FILE__, __LINE__); \
* exit(1); \
* } \
* } while(0)
*
* ============================================================================
*/