c
examples
examples.c🔧c
/**
* @file examples.c
* @brief Comments and Documentation Examples in C
*
* This file demonstrates various commenting styles and
* documentation practices in C programming.
*
* @author Learn C Course
* @date 2024
* @version 1.0
*
* Compile: gcc -Wall examples.c -o examples
* Run: ./examples
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* ============================================================
* SECTION 1: SINGLE-LINE COMMENTS
* ============================================================ */
/**
* @brief Demonstrates single-line comment usage.
*/
void example_single_line_comments() {
printf("\n=== Example 1: Single-Line Comments ===\n");
// This is a single-line comment
int x = 10; // Initialize x to 10
// You can have multiple
// single-line comments
// one after another
int y = 20; // Comment at end of line
printf("x = %d, y = %d\n", x, y);
// Single-line comments are great for:
// - Brief explanations
// - Temporary notes
// - Disabling single lines
// printf("This line is commented out\n");
printf("This line will print\n");
}
/* ============================================================
* SECTION 2: MULTI-LINE COMMENTS
* ============================================================ */
/**
* @brief Demonstrates multi-line comment usage.
*/
void example_multi_line_comments() {
printf("\n=== Example 2: Multi-Line Comments ===\n");
/* This is a basic multi-line comment.
It can span multiple lines and is
useful for longer explanations. */
/*
* This is a more stylized multi-line
* comment with asterisks at the start
* of each line for better readability.
*/
/* Single line works too */
int a = 5, /* inline comment */ b = 10;
printf("a = %d, b = %d\n", a, b);
/* Multi-line comments can be used to
comment out large blocks of code:
printf("This won't print\n");
printf("Neither will this\n");
*/
printf("Multi-line comments demonstrated\n");
}
/* ============================================================
* SECTION 3: DOCUMENTATION COMMENTS
* ============================================================ */
/**
* @brief Calculates the area of a rectangle.
*
* This function computes the area by multiplying
* width and height. Both parameters must be positive.
*
* @param width The width of the rectangle (must be > 0)
* @param height The height of the rectangle (must be > 0)
* @return The area of the rectangle, or -1 if invalid input
*
* @note This is a simple implementation without overflow checking.
* @warning For large values, result may overflow.
*
* @example
* float area = calculateArea(5.0f, 3.0f); // area = 15.0
*/
float calculateArea(float width, float height) {
// Validate input
if (width <= 0 || height <= 0) {
return -1.0f;
}
return width * height;
}
/**
* @brief Demonstrates documentation comment style.
*/
void example_documentation_comments() {
printf("\n=== Example 3: Documentation Comments ===\n");
float area1 = calculateArea(5.0f, 3.0f);
float area2 = calculateArea(-1.0f, 5.0f);
printf("Area(5, 3) = %.2f\n", area1);
printf("Area(-1, 5) = %.2f (invalid input)\n", area2);
}
/* ============================================================
* SECTION 4: EXPLAINING COMPLEX LOGIC
* ============================================================ */
/**
* @brief Finds the greatest common divisor using Euclidean algorithm.
*
* The Euclidean algorithm is based on the principle that
* gcd(a, b) = gcd(b, a mod b), and gcd(a, 0) = a.
*
* @param a First positive integer
* @param b Second positive integer
* @return GCD of a and b
*/
int gcd(int a, int b) {
/*
* Euclidean Algorithm:
* 1. If b is 0, return a (base case)
* 2. Otherwise, return gcd(b, a % b)
*
* Example: gcd(48, 18)
* - gcd(48, 18) -> gcd(18, 48 % 18) = gcd(18, 12)
* - gcd(18, 12) -> gcd(12, 18 % 12) = gcd(12, 6)
* - gcd(12, 6) -> gcd(6, 12 % 6) = gcd(6, 0)
* - gcd(6, 0) -> return 6
*/
while (b != 0) {
int temp = b; // Save b before overwriting
b = a % b; // New b is remainder of a/b
a = temp; // New a is old b
}
return a;
}
void example_algorithm_comments() {
printf("\n=== Example 4: Algorithm Comments ===\n");
int result = gcd(48, 18);
printf("GCD(48, 18) = %d\n", result);
result = gcd(100, 25);
printf("GCD(100, 25) = %d\n", result);
}
/* ============================================================
* SECTION 5: TODO AND FIXME COMMENTS
* ============================================================ */
/**
* @brief Demonstrates TODO and FIXME markers.
*/
void example_todo_fixme() {
printf("\n=== Example 5: TODO and FIXME Markers ===\n");
// TODO: Add input validation for negative numbers
int values[] = {5, 10, 15};
// FIXME: This calculation is incorrect for edge cases
int sum = values[0] + values[1] + values[2];
// HACK: Temporary fix until library is updated
int adjusted = sum + 1;
// NOTE: Array must have exactly 3 elements
printf("Sum = %d, Adjusted = %d\n", sum, adjusted);
// XXX: Potential performance issue with large arrays
// OPTIMIZE: Could use SIMD instructions for better performance
printf("Check source code for marker examples\n");
}
/* ============================================================
* SECTION 6: COMMENTING DATA STRUCTURES
* ============================================================ */
/**
* @struct Point
* @brief Represents a point in 2D space.
*/
typedef struct {
int x; /**< X coordinate */
int y; /**< Y coordinate */
} Point;
/**
* @struct Rectangle
* @brief Represents a rectangle with position and size.
*/
typedef struct {
Point topLeft; /**< Top-left corner position */
int width; /**< Width of rectangle (must be > 0) */
int height; /**< Height of rectangle (must be > 0) */
char name[32]; /**< Optional name identifier */
} Rectangle;
/**
* @enum Color
* @brief Predefined color values.
*/
typedef enum {
COLOR_RED = 0, /**< RGB: 255, 0, 0 */
COLOR_GREEN, /**< RGB: 0, 255, 0 */
COLOR_BLUE, /**< RGB: 0, 0, 255 */
COLOR_WHITE, /**< RGB: 255, 255, 255 */
COLOR_BLACK /**< RGB: 0, 0, 0 */
} Color;
void example_struct_comments() {
printf("\n=== Example 6: Data Structure Comments ===\n");
Rectangle rect = {
.topLeft = {10, 20},
.width = 100,
.height = 50,
.name = "MainWindow"
};
printf("Rectangle '%s':\n", rect.name);
printf(" Position: (%d, %d)\n", rect.topLeft.x, rect.topLeft.y);
printf(" Size: %d x %d\n", rect.width, rect.height);
Color c = COLOR_GREEN;
printf(" Color: %d (GREEN)\n", c);
}
/* ============================================================
* SECTION 7: CONDITIONAL COMPILATION AS COMMENTS
* ============================================================ */
// Define DEBUG to enable debug output
#define DEBUG 1
void example_conditional_comments() {
printf("\n=== Example 7: Conditional Compilation ===\n");
int value = 42;
#ifdef DEBUG
// This only compiles when DEBUG is defined
printf("[DEBUG] value = %d\n", value);
printf("[DEBUG] address of value = %p\n", (void*)&value);
#endif
printf("Value is: %d\n", value);
#if 0
// This code is "commented out" using preprocessor
// The compiler completely ignores this section
printf("This will never print\n");
printf("This is effectively a block comment\n");
This even works with invalid code!
#endif
printf("Conditional compilation demonstrated\n");
}
/* ============================================================
* SECTION 8: SELF-DOCUMENTING CODE
* ============================================================ */
// Constants with descriptive names
#define MINIMUM_AGE_FOR_VOTING 18
#define MAXIMUM_LOGIN_ATTEMPTS 3
#define MILLISECONDS_PER_SECOND 1000
/**
* @brief Demonstrates self-documenting code style.
*
* When code is self-documenting, fewer comments are needed.
*/
void example_self_documenting() {
printf("\n=== Example 8: Self-Documenting Code ===\n");
// Bad: needs comment to explain
// int x = 18; // Voting age
// Good: self-explanatory
int minimumVotingAge = MINIMUM_AGE_FOR_VOTING;
int userAge = 21;
// Bad: cryptic condition
// if (a >= 18)
// Good: intention is clear
int canVote = (userAge >= minimumVotingAge);
// Bad: magic numbers
// int delay = 1000;
// Good: named constant
int delayInMilliseconds = 2 * MILLISECONDS_PER_SECOND;
printf("Voting age: %d\n", minimumVotingAge);
printf("User can vote: %s\n", canVote ? "Yes" : "No");
printf("Delay: %d ms\n", delayInMilliseconds);
}
/* ============================================================
* SECTION 9: INLINE COMMENT EXAMPLES
* ============================================================ */
/**
* @brief Checks if a year is a leap year.
* @param year The year to check
* @return 1 if leap year, 0 otherwise
*/
int isLeapYear(int year) {
// A year is a leap year if:
// - Divisible by 4 AND
// - NOT divisible by 100, UNLESS also divisible by 400
return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}
void example_inline_comments() {
printf("\n=== Example 9: Inline Comments ===\n");
int years[] = {2000, 2020, 2100, 2024};
int count = sizeof(years) / sizeof(years[0]);
for (int i = 0; i < count; i++) {
int year = years[i];
int leap = isLeapYear(year);
printf("%d is %sa leap year\n", year, leap ? "" : "not ");
}
}
/* ============================================================
* SECTION 10: HEADER SECTION DIVIDERS
* ============================================================ */
/**
* @brief Demonstrates section divider styles.
*/
void example_section_dividers() {
printf("\n=== Example 10: Section Dividers ===\n");
printf("Check the source code for different\n");
printf("section divider styles:\n\n");
printf("Style 1: /* ==== SECTION ==== */\n");
printf("Style 2: // ---- Section ----\n");
printf("Style 3: /***********************\n");
printf(" * Section Header *\n");
printf(" ***********************/\n");
printf("Style 4: #pragma mark - Section (Xcode)\n");
printf("Style 5: //region Section (VS Code)\n");
}
/* ============================================================
* MAIN FUNCTION
* ============================================================ */
/**
* @brief Main entry point of the program.
*
* Runs all comment examples to demonstrate
* different documentation styles.
*
* @return 0 on successful execution
*/
int main() {
printf("╔════════════════════════════════════════════════╗\n");
printf("║ COMMENTS AND DOCUMENTATION - EXAMPLES ║\n");
printf("║ Learn how to document C code ║\n");
printf("╚════════════════════════════════════════════════╝\n");
example_single_line_comments();
example_multi_line_comments();
example_documentation_comments();
example_algorithm_comments();
example_todo_fixme();
example_struct_comments();
example_conditional_comments();
example_self_documenting();
example_inline_comments();
example_section_dividers();
printf("\n=== All Examples Completed! ===\n");
return 0; // Return success
}