fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. #define defer(stmt) __defer__ __defer__var__ = {stmt}
  6.  
  7. // A structure to hold the deferred statement
  8. typedef struct {
  9. void (*stmt)(void);
  10. } __defer__;
  11.  
  12. // Define the defer structure with a cleanup function
  13. void cleanup(void) {
  14. printf("Cleaning up resources.\n");
  15. }
  16.  
  17. // The main function that uses the defer mechanism
  18. int main(void) {
  19. // Dynamic memory allocation
  20. char *test = malloc(14 * sizeof(char));
  21. if (!test) {
  22. perror("malloc failed");
  23. return 1;
  24. }
  25.  
  26. // Initialize the string
  27. strncpy(test, "Hello, World!", 13);
  28. test[13] = '\0'; // null-terminate properly
  29.  
  30. // Print the string
  31. printf("test string = \"%s\"\n", test);
  32.  
  33. // Using the defer macro
  34. defer(cleanup); // The deferred cleanup will be run on scope exit
  35.  
  36. // After the defer statement is invoked, you can write more code here.
  37. // But cleanup happens automatically when the scope exits.
  38.  
  39. // Manually free memory
  40. free(test);
  41.  
  42. // The deferred code will execute when we reach this point in the code.
  43. return 0;
  44.  
  45. // Defer will be executed after this point, simulating Zig's defer behavior.
  46. }
  47.  
Success #stdin #stdout 0.01s 5288KB
stdin
Standard input is empty
stdout
test string = "Hello, World!"