### C Example: Epoch Start Time Output Source: https://devdocs.io/c/chrono/time_t Shows the possible output when running the example code to display the epoch start time. ```c 0 seconds since the epoch began Thu Jan 1 00:00:00 1970 ``` -------------------------------- ### C Example: Displaying Epoch Start Time Source: https://devdocs.io/c/chrono/time_t Demonstrates how to display the start of the epoch (0 seconds since epoch) and its corresponding date and time using time_t, gmtime, and asctime. ```c #include #include #include int main(void) { time_t epoch = 0; printf("%jd seconds since the epoch began\n", (intmax_t)epoch); printf("%s", asctime(gmtime(&epoch))); } ``` -------------------------------- ### Example: Demonstrating fegetround and fesetround Source: https://devdocs.io/c/numeric/fenv/feround This example demonstrates how to use `fegetround` to get the current rounding direction and `fesetround` to temporarily change it. It shows the effect of different rounding modes on the `rint` function. ```c #include #include #include // #pragma STDC FENV_ACCESS ON void show_fe_current_rounding_direction(void) { printf("current rounding direction: "); switch (fegetround()) { case FE_TONEAREST: printf ("FE_TONEAREST"); break; case FE_DOWNWARD: printf ("FE_DOWNWARD"); break; case FE_UPWARD: printf ("FE_UPWARD"); break; case FE_TOWARDZERO: printf ("FE_TOWARDZERO"); break; default: printf ("unknown"); }; printf("\n"); } int main(void) { /* Default rounding direction */ show_fe_current_rounding_direction(); printf("+11.5 -> %+4.1f\n", rint(+11.5)); /* midway between two integers */ printf("+12.5 -> %+4.1f\n", rint(+12.5)); /* midway between two integers */ /* Save current rounding direction. */ int curr_direction = fegetround(); /* Temporarily change current rounding direction. */ fesetround(FE_DOWNWARD); show_fe_current_rounding_direction(); printf("+11.5 -> %+4.1f\n", rint(+11.5)); printf("+12.5 -> %+4.1f\n", rint(+12.5)); /* Restore default rounding direction. */ fesetround(curr_direction); show_fe_current_rounding_direction(); return 0; } ``` -------------------------------- ### C Example: Using signal and SIG_ERR Source: https://devdocs.io/c/program/sig_err This example demonstrates how to install a signal handler using the `signal` function and check for errors using `SIG_ERR`. It then raises a signal and handles potential errors. ```c #include #include #include void signal_handler(int sig) { printf("Received signal: %d\n", sig); } int main(void) { /* Install a signal handler. */ if (signal(SIGTERM, signal_handler) == SIG_ERR) { printf("Error while installing a signal handler.\n"); exit(EXIT_FAILURE); } printf("Sending signal: %d\n", SIGTERM); if (raise(SIGTERM) != 0) { printf("Error while raising the SIGTERM signal.\n"); exit(EXIT_FAILURE); } printf("Exit main()\n"); return EXIT_SUCCESS; } ``` -------------------------------- ### Example of using raise() to send SIGTERM Source: https://devdocs.io/c/program/raise This example demonstrates how to install a signal handler for SIGTERM and then use raise() to send that signal. The output shows the sequence of events, including the signal handler being invoked. ```c #include #include void signal_handler(int signal) { printf("Received signal %d\n", signal); } int main(void) { // Install a signal handler. signal(SIGTERM, signal_handler); printf("Sending signal %d\n", SIGTERM); raise(SIGTERM); printf("Exit main()\n"); } ``` -------------------------------- ### Example output of C for loop Source: https://devdocs.io/c/language/for Shows a possible output for the C for loop example that fills and prints an array. ```text Array filled! 1 0 1 1 1 1 0 0 ``` -------------------------------- ### Output of puts Example Source: https://devdocs.io/c/io/puts The expected output when the example C code using puts is executed. ```text Hello World ``` -------------------------------- ### Example output of time() usage Source: https://devdocs.io/c/chrono/time A sample output illustrating the format of the current time and seconds since the Epoch as produced by the example code. ```text The current time is Fri Apr 24 15:05:25 2015 (1429887925 seconds since the Epoch) ``` -------------------------------- ### C isgreater example output Source: https://devdocs.io/c/numeric/math/isgreater Shows the expected output when running the example code that utilizes the `isgreater` macro. ```text isgreater(2.0,1.0) = 1 isgreater(1.0,2.0) = 0 isgreater(INFINITY,1.0) = 1 isgreater(1.0,NAN) = 0 ``` -------------------------------- ### C return statement example Source: https://devdocs.io/c/language/return Demonstrates the usage of the return statement in C functions. Includes examples for void functions and functions returning integer values. ```c #include void fa(int i) { if (i == 2) return; printf("fa(): %d\n", i); } // implied return; int fb(int i) { if (i > 4) return 4; printf("fb(): %d\n", i); return 2; } int main(void) { fa(2); fa(1); int i = fb(5); // the return value 4 used to initializes i i = fb(i); // the return value 2 used as rhs of assignment printf("main(): %d\n", i); } ``` -------------------------------- ### Example usage of frexp Source: https://devdocs.io/c/numeric/math/frexp This example demonstrates how to use frexp to decompose a floating-point number and compares its output with modf and ilogb. It also shows how to reconstruct the number using scalbn. ```c #include #include #include int main(void) { double f = 123.45; printf("Given the number %.2f or %a in hex,\n", f, f); double f3; double f2 = modf(f, &f3); printf("modf() makes %.0f + %.2f\n", f3, f2); int i; f2 = frexp(f, &i); printf("frexp() makes %f * 2^%d\n", f2, i); i = ilogb(f); printf("logb()/ilogb() make %f * %d^%d\n", f/scalbn(1.0, i), FLT_RADIX, i); } ``` -------------------------------- ### C Predefined Macros Example Source: https://devdocs.io/c/preprocessor/replace Demonstrates the usage of function-like macros, stringification, and redefining macros. This example shows how to create macros that generate functions and how to use the stringification operator (#). ```c #include // make function factory and use it #define FUNCTION(name, a) int fun_##name(int x) { return (a) * x; } FUNCTION(quadruple, 4) FUNCTION(double, 2) #undef FUNCTION #define FUNCTION 34 #define OUTPUT(a) puts( #a ) int main(void) { printf("quadruple(13): %d\n", fun_quadruple(13) ); printf("double(21): %d\n", fun_double(21) ); printf("%d\n", FUNCTION); OUTPUT(billion); // note the lack of quotes } ``` ```text quadruple(13): 52 double(21): 42 34 billion ``` -------------------------------- ### Example Usage of max_align_t and malloc Alignment Source: https://devdocs.io/c/types/max_align_t This example demonstrates how to get the alignment requirement of `max_align_t` using `alignof` and shows that pointers returned by `malloc` are suitably aligned for any object. ```c #include #include #include #include #include #include int main(void) { size_t a = alignof(max_align_t); printf("Alignment of max_align_t is %zu (%#zx)\n", a, a); void *p = malloc(123); printf("The address obtained from malloc(123) is %#" PRIxPTR "\n", (uintptr_t)p); free(p); } ``` -------------------------------- ### C Initialization Examples Source: https://devdocs.io/c/language/initialization Demonstrates various ways to initialize variables and arrays in C, including automatic, static, and aggregate types. Shows initialization with specific values, default zeroing for arrays, and initialization of arrays of structs. ```c #include int a[2]; // initializes a to {0, 0} int main(void) { int i; // initializes i to an indeterminate value static int j; // initializes j to 0 int k = 1; // initializes k to 1 // initializes int x[3] to 1,3,5 // initializes int* p to &x[0] int x[] = { 1, 3, 5 }, *p = x; // initializes w (an array of two structs) to // { { {1,0,0}, 0}, { {2,0,0}, 0} } struct {int a[3], b;} w[] = {[0].a = {1}, [1].a[0] = 2}; // function call expression can be used for a local variable char* ptr = malloc(10); free(ptr); // Error: objects with static storage duration require constant initializers // static char* ptr = malloc(10); // Error: VLA cannot be initialized // int vla[n] = {0}; } ``` -------------------------------- ### Example of using system() to run commands Source: https://devdocs.io/c/program/system This example demonstrates how to use the `system()` function to execute a Unix `date` command and a `gcc` compiler command with its version flag. Ensure the commands are available in your host environment. ```c #include int main(void) { system("date +%A"); system("gcc --version"); } ``` -------------------------------- ### C Example: Demonstrating Floating-Point Environment Manipulation Source: https://devdocs.io/c/numeric/fenv/fe_dfl_env This example demonstrates how to query and manipulate the floating-point environment, including exceptions and rounding modes, and how to restore the default environment using FE_DFL_ENV. ```c #include #include #pragma STDC FENV_ACCESS ON void show_fe_exceptions(void) { printf("current exceptions raised: "); if(fetestexcept(FE_DIVBYZERO)) printf(" FE_DIVBYZERO"); if(fetestexcept(FE_INEXACT)) printf(" FE_INEXACT"); if(fetestexcept(FE_INVALID)) printf(" FE_INVALID"); if(fetestexcept(FE_OVERFLOW)) printf(" FE_OVERFLOW"); if(fetestexcept(FE_UNDERFLOW)) printf(" FE_UNDERFLOW"); if(fetestexcept(FE_ALL_EXCEPT)==0) printf(" none"); printf("\n"); } void show_fe_rounding_method(void) { printf("current rounding method: "); switch (fegetround()) { case FE_TONEAREST: printf ("FE_TONEAREST"); break; case FE_DOWNWARD: printf ("FE_DOWNWARD"); break; case FE_UPWARD: printf ("FE_UPWARD"); break; case FE_TOWARDZERO: printf ("FE_TOWARDZERO"); break; default: printf ("unknown"); }; printf("\n"); } void show_fe_environment(void) { show_fe_exceptions(); show_fe_rounding_method(); } int main() { printf("On startup:\n"); show_fe_environment(); // Change environment fesetround(FE_DOWNWARD); // change rounding mode feraiseexcept(FE_INVALID); // raise exception printf("\nBefore restoration:\n"); show_fe_environment(); fesetenv(FE_DFL_ENV); // restore printf("\nAfter restoring default environment:\n"); show_fe_environment(); } ``` -------------------------------- ### C Example: Summing Variadic Arguments (C99 and C23) Source: https://devdocs.io/c/variadic/va_start Demonstrates using va_start to sum a variable number of integers passed to a function. Includes C99 and C23 compliant versions. ```c #include #include int add_nums_C99(int count, ...) { int result = 0; va_list args; va_start(args, count); // count can be omitted since C23 for (int i = 0; i < count; ++i) { result += va_arg(args, int); } va_end(args); return result; } #if __STDC_VERSION__ > 201710L // Same as above, valid since C23 int add_nums_C23(...) { int result = 0; va_list args; va_start(args); int count = va_arg(args, int); for (int i = 0; i < count; ++i) { result += va_arg(args, int); } va_end(args); return result; } #endif int main(void) { printf("%d\n", add_nums_C99(4, 25, 25, 50, 50)); #if __STDC_VERSION__ > 201710L printf("%d\n", add_nums_C23(4, 25, 25, 50, 50)); #endif } ``` -------------------------------- ### Registering functions with atexit() Source: https://devdocs.io/c/program/atexit This example demonstrates how to register multiple functions, including duplicates, using `atexit()`. It shows successful registration and the order of execution upon program termination. ```c #include #include void f1(void) { puts("f1"); } void f2(void) { puts("f2"); } int main(void) { if ( ! atexit(f1) && ! atexit(f2) && ! atexit(f2) ) return EXIT_SUCCESS ; // atexit registration failed return EXIT_FAILURE ; } // <- if registration was successful calls f2, f2, f1 ``` -------------------------------- ### Get current time using time() and display it Source: https://devdocs.io/c/chrono/time This example demonstrates how to use the time() function to get the current calendar time and then display it in a human-readable format using asctime() and gmtime(). It also shows the time in seconds since the Epoch. ```c #include #include #include int main(void) { time_t result = time(NULL); if(result != (time_t)(-1)) printf("The current time is %s(%jd seconds since the Epoch)\n", asctime(gmtime(&result)), (intmax_t)result); } ``` -------------------------------- ### Example Usage of unreachable Macro Source: https://devdocs.io/c/program/unreachable This example demonstrates how to use the `unreachable` macro within a switch statement to handle cases that should logically not occur. It includes setup for color structures and memory allocation, and uses `assert` to verify expected behavior. ```c #include #include #include #include struct Color { uint8_t r, g, b, a; }; struct ColorSpan { struct Color* data; size_t size; }; // Assume that only restricted set of texture caps is supported. struct ColorSpan allocate_texture(size_t xy) { switch (xy) { case 128: [[fallthrough]]; case 256: [[fallthrough]]; case 512: { /* ... */ struct ColorSpan result = { .data = malloc(xy * xy * sizeof(struct Color)), .size = xy * xy }; if (!result.data) result.size = 0; return result; } default: unreachable(); } } int main(void) { struct ColorSpan tex = allocate_texture(128); // OK assert(tex.size == 128 * 128); struct ColorSpan badtex = allocate_texture(32); // Undefined behavior free(badtex.data); free(tex.data); } ``` -------------------------------- ### C Array Initialization Examples Source: https://devdocs.io/c/language/array_initialization Demonstrates various ways to initialize multi-dimensional arrays and arrays with string literals using designated initializers in C. These examples show equivalent initialization methods. ```c int main(void) { // The following four array declarations are the same short q1[4][3][2] = { { 1 }, { 2, 3 }, { 4, 5, 6 } }; short q2[4][3][2] = {1, 0, 0, 0, 0, 0, 2, 3, 0, 0, 0, 0, 4, 5, 6}; short q3[4][3][2] = { { { 1 }, }, { { 2, 3 }, }, { { 4, 5 }, { 6 }, } }; short q4[4][3][2] = {1, [1]=2, 3, [2]=4, 5, 6}; // Character names can be associated with enumeration constants // using arrays with designators: enum { RED, GREEN, BLUE }; const char *nm[] = { [RED] = "red", [GREEN] = "green", [BLUE] = "blue", }; } ``` -------------------------------- ### Example of using sig_atomic_t for signal handling Source: https://devdocs.io/c/program/sig_atomic_t This example demonstrates how to use `sig_atomic_t` to safely handle signals, specifically `SIGINT`, by installing a signal handler that updates a global status variable. The variable `gSignalStatus` is declared as `volatile sig_atomic_t` to ensure atomic access. ```c #include #include volatile sig_atomic_t gSignalStatus = 0; void signal_handler(int status) { gSignalStatus = status; } int main(void) { /* Install a signal handler. */ signal(SIGINT, signal_handler); printf("SignalValue: %d\n", gSignalStatus); printf("Sending signal: %d\n", SIGINT); raise(SIGINT); printf("SignalValue: %d\n", gSignalStatus); } ``` -------------------------------- ### Example Usage of quick_exit Source: https://devdocs.io/c/program/quick_exit Demonstrates registering functions with at_quick_exit and atexit, then calling quick_exit. Functions registered with at_quick_exit are called, while the one with atexit is not. ```c #include #include void f1(void) { puts("pushed first"); fflush(stdout); } void f2(void) { puts("pushed second"); } void f3(void) { puts("won't be called"); } int main(void) { at_quick_exit(f1); at_quick_exit(f2); atexit(f3); quick_exit(0); } ``` -------------------------------- ### C Application Code Example (main.c) Source: https://devdocs.io/c/language/storage_duration This C source file demonstrates how to use declarations from 'flib.h'. It accesses constants, variables, and functions defined in the library. ```c #include "flib.h" int main(void) { int x[MAX] = {size}; // uses the constant and the read-only variable state = 7; // modifies state in flib.c f(); // calls f() in flib.c } ``` -------------------------------- ### Example Usage of abs Function Source: https://devdocs.io/c/numeric/math/abs Demonstrates how to use the abs function to get the absolute value of positive and negative integers. The example includes standard headers and prints the results. Note that calling abs with INT_MIN on 2's complement systems results in undefined behavior. ```c #include #include #include int main(void) { printf("abs(+3) = %d\n", abs(+3)); printf("abs(-3) = %d\n", abs(-3)); // printf("%+d\n", abs(INT_MIN)); // undefined behavior on 2's complement systems } ``` -------------------------------- ### C feholdexcept() Example Source: https://devdocs.io/c/numeric/fenv/feholdexcept Demonstrates saving the floating-point environment, clearing exceptions, and updating the environment. This example shows how to use `feholdexcept` to manage floating-point exceptions within a function and how `feupdateenv` can be used to restore the environment and raise specific exceptions. ```c #include #include #include #pragma STDC FENV_ACCESS ON void show_fe_exceptions(void) { printf("current exceptions raised: "); if(fetestexcept(FE_DIVBYZERO)) printf(" FE_DIVBYZERO"); if(fetestexcept(FE_INEXACT)) printf(" FE_INEXACT"); if(fetestexcept(FE_INVALID)) printf(" FE_INVALID"); if(fetestexcept(FE_OVERFLOW)) printf(" FE_OVERFLOW"); if(fetestexcept(FE_UNDERFLOW)) printf(" FE_UNDERFLOW"); if(fetestexcept(FE_ALL_EXCEPT)==0) printf(" none"); printf("\n"); } double x2 (double x) /* times two */ { fenv_t curr_excepts; /* Save and clear current f-p environment. */ feholdexcept(&curr_excepts); /* Raise inexact and overflow exceptions. */ printf("In x2(): x = %f\n", x=x*2.0); show_fe_exceptions(); feclearexcept(FE_INEXACT); /* hide inexact exception from caller */ /* Merge caller's exceptions (FE_INVALID) */ /* with remaining x2's exceptions (FE_OVERFLOW). */ feupdateenv(&curr_excepts); return x; } int main(void) { feclearexcept(FE_ALL_EXCEPT); feraiseexcept(FE_INVALID); /* some computation with invalid argument */ show_fe_exceptions(); printf("x2(DBL_MAX) = %f\n", x2(DBL_MAX)); show_fe_exceptions(); return 0; } ``` -------------------------------- ### C ftell() Example Source: https://devdocs.io/c/io/ftell Demonstrates using ftell() to get the file position indicator before and after reading data from a binary file. Includes error checking for file operations. ```c #include #include /* If the condition is not met then exit the program with error message. */ void check(_Bool condition, const char* func, int line) { if (condition) return; perror(func); fprintf(stderr, "%s failed in file %s at line # %d\n", func, __FILE__, line - 1); exit(EXIT_FAILURE); } int main(void) { /* Prepare an array of FP values. */ #define SIZE 5 double A[SIZE] = {1.1,2.,3.,4.,5.}; /* Write array to a file. */ const char* fname = "/tmp/test.bin"; FILE* file = fopen(fname, "wb"); check(file != NULL, "fopen()", __LINE__); const int write_count = fwrite(A, sizeof(double), SIZE, file); check(write_count == SIZE, "fwrite()", __LINE__); fclose(file); /* Read the FP values into array B. */ double B[SIZE]; file = fopen(fname, "rb"); check(file != NULL, "fopen()", __LINE__); long int pos = ftell(file); /* position indicator at start of file */ check(pos != -1L, "ftell()", __LINE__); printf("pos: %ld\n", pos); const int read_count = fread(B, sizeof(double), 1, file); /* read one FP value */ check(read_count == 1, "fread()", __LINE__); pos = ftell(file); /* position indicator after reading one FP value */ check(pos != -1L, "ftell()", __LINE__); printf("pos: %ld\n", pos); printf("B[0]: %.1f\n", B[0]); /* print one FP value */ return EXIT_SUCCESS; } ``` -------------------------------- ### Example: Optimizing File Buffer Size with setvbuf Source: https://devdocs.io/c/io/setvbuf Demonstrates using setvbuf to set a file stream's buffer to an optimal size determined by fstat, improving I/O efficiency. Requires POSIX functions. ```c #define _POSIX_SOURCE #include #include #include int main(void) { FILE* fp = fopen("/tmp/test.txt", "w+"); if (fp == NULL) { perror("fopen"); return EXIT_FAILURE; } struct stat stats; if (fstat(fileno(fp), &stats) == -1) // POSIX only { perror("fstat"); return EXIT_FAILURE; } printf("BUFSIZ is %d, but optimal block size is %ld\n", BUFSIZ, stats.st_blksize); if (setvbuf(fp, NULL, _IOFBF, stats.st_blksize) != 0) { perror("setvbuf failed"); // POSIX version sets errno return EXIT_FAILURE; } int ch; while((ch=fgetc(fp)) != EOF); // read entire file: use truss/strace to // observe the read(2) syscalls used fclose(fp); return EXIT_SUCCESS; } ``` -------------------------------- ### Using localeconv to Get Locale Formatting Source: https://devdocs.io/c/locale/localeconv This example demonstrates how to use `localeconv` to retrieve and print currency symbols for a specific locale. Ensure the locale is set using `setlocale` before calling `localeconv`. ```c #include #include int main(void) { setlocale(LC_MONETARY, "en_IN.utf8"); struct lconv *lc = localeconv(); printf("Local Currency Symbol : %s\n", lc->currency_symbol); printf("International Currency Symbol: %s\n", lc->int_curr_symbol); } ``` -------------------------------- ### C strcpy and strcpy_s String Copy Example Source: https://devdocs.io/c/string/byte/strcpy Demonstrates the usage of both the traditional `strcpy` and the bounds-checked `strcpy_s` functions for copying strings in C. Includes setup for `strcpy_s` and shows error handling. ```c #define __STDC_WANT_LIB_EXT1__ 1 #include #include #include int main(void) { const char *src = "Take the test."; // src[0] = 'M' ; // this would be undefined behavior char dst[strlen(src) + 1]; // +1 to accommodate for the null terminator strcpy(dst, src); dst[0] = 'M'; // OK printf("src = %s\ndst = %s\n", src, dst); #ifdef __STDC_LIB_EXT1__ set_constraint_handler_s(ignore_handler_s); int r = strcpy_s(dst, sizeof dst, src); printf("dst = \"%s\", r = %d\n", dst, r); r = strcpy_s(dst, sizeof dst, "Take even more tests."); printf("dst = \"%s\", r = %d\n", dst, r); #endif } ``` -------------------------------- ### C asin Example Usage Source: https://devdocs.io/c/numeric/math/asin This example demonstrates how to use the asin function, including handling special values like zero and demonstrating error conditions for arguments outside the valid domain [-1.0, 1.0]. It also shows how to check for domain errors using errno and floating-point exceptions. ```c #include #include #include #include #include #ifndef __GNUC__ #pragma STDC FENV_ACCESS ON #endif int main(void) { printf("asin( 1.0) = %+f, 2*asin( 1.0)=%+f\n", asin(1), 2 * asin(1)); printf("asin(-0.5) = %+f, 6*asin(-0.5)=%+f\n", asin(-0.5), 6 * asin(-0.5)); // special values printf("asin(0.0) = %1f, asin(-0.0)=%f\n", asin(+0.0), asin(-0.0)); // error handling errno = 0; feclearexcept(FE_ALL_EXCEPT); printf("asin(1.1) = %f\n", asin(1.1)); if (errno == EDOM) perror(" errno == EDOM"); if (fetestexcept(FE_INVALID)) puts(" FE_INVALID raised"); } ``` -------------------------------- ### Using strerror and locale-specific error messages Source: https://devdocs.io/c/string/byte/strerror Demonstrates how to use strerror to get an error message and how to change the locale to retrieve messages in different languages. This example also shows the usage of the thread-safe strerror_s and strerrorlen_s functions if the __STDC_LIB_EXT1__ macro is defined. ```c #define __STDC_WANT_LIB_EXT1__ 1 #include #include #include #include int main(void) { FILE *fp = fopen(tmpnam((char[L_tmpnam]){0}), "r"); if(fp==NULL) { printf("File opening error: %s\n", strerror(errno)); setlocale(LC_MESSAGES, "de_DE.utf8"); printf("Now in German: %s\n", strerror(errno)); #ifdef __STDC_LIB_EXT1__ setlocale(LC_ALL, "ja_JP.utf8"); // printf needs CTYPE for multibyte output size_t errmsglen = strerrorlen_s(errno) + 1; char errmsg[errmsglen]; strerror_s(errmsg, errmsglen, errno); printf("Now in Japanese: %s\n", errmsg); #endif } } ``` -------------------------------- ### C memcpy and memcpy_s Example Source: https://devdocs.io/c/string/byte/memcpy Demonstrates the usage of memcpy for basic memory copying, setting effective types, and reinterpreting data. Also shows the safe version, memcpy_s, with error handling for buffer overflows. ```c #define __STDC_WANT_LIB_EXT1__ 1 #include #include #include #include #include int main(void) { // simple usage char source[] = "once upon a midnight dreary...", dest[4]; memcpy(dest, source, sizeof dest); for(size_t n = 0; n < sizeof dest; ++n) putchar(dest[n]); // setting effective type of allocated memory to be int int *p = malloc(3*sizeof(int)); // allocated memory has no effective type int arr[3] = {1,2,3}; memcpy(p,arr,3*sizeof(int)); // allocated memory now has an effective type // reinterpreting data double d = 0.1; // int64_t n = *(int64_t*)(&d); // strict aliasing violation int64_t n; memcpy(&n, &d, sizeof d); // OK printf("\n%a is %\"% ``` ```c PRIx64 " as an int64_t\n", d, n); #ifdef __STDC_LIB_EXT1__ set_constraint_handler_s(ignore_handler_s); char src[] = "aaaaaaaaaa"; char dst[] = "xyxyxyxyxy"; int r = memcpy_s(dst,sizeof dst,src,5); printf("dst = \"%s\", r = %d\n", dst,r); r = memcpy_s(dst,5,src,10); // count is greater than destsz printf("dst = \""); for(size_t ndx=0; ndx #include int main(void) { FILE* fp = fopen("from.txt", "w"); // create file "from.txt" if (!fp) { perror("from.txt"); return EXIT_FAILURE; } fputc('a', fp); // write to "from.txt" fclose(fp); int rc = rename("from.txt", "to.txt"); if (rc) { perror("rename"); return EXIT_FAILURE; } fp = fopen("to.txt", "r"); if(!fp) { perror("to.txt"); return EXIT_FAILURE; } printf("%c\n", fgetc(fp)); // read from "to.txt" fclose(fp); return EXIT_SUCCESS; } ``` -------------------------------- ### Example usage of float_t and double_t Source: https://devdocs.io/c/numeric/math/float_t This example demonstrates how to check the `FLT_EVAL_METHOD` and compare the sizes of `float` with `float_t` and `double` with `double_t`. Include ``, ``, and `` for this example. ```c #include #include #include int main(void) { printf("%d\n", FLT_EVAL_METHOD); printf("%zu %zu\n", sizeof(float),sizeof(float_t)); printf("%zu %zu\n", sizeof(double),sizeof(double_t)); return 0; } ``` -------------------------------- ### Example Usage of memset and memset_s Source: https://devdocs.io/c/string/byte/memset Demonstrates the usage of memset for basic memory filling and memset_s for secure memory filling with error handling. It shows how to set a string to a specific character and how memset_s detects and reports errors. ```c #define __STDC_WANT_LIB_EXT1__ 1 #include #include #include int main(void) { char str[] = "ghghghghghghghghghghgh"; puts(str); memset(str,'a',5); puts(str); #ifdef __STDC_LIB_EXT1__ set_constraint_handler_s(ignore_handler_s); int r = memset_s(str, sizeof str, 'b', 5); printf("str = \"%s\", r = %d\n", str, r); r = memset_s(str, 5, 'c', 10); // count is greater than destsz printf("str = \"%s\", r = %d\n", str, r); #endif } ``` -------------------------------- ### Example: Working with Complex Numbers in C Source: https://devdocs.io/c/numeric/complex/complex Demonstrates the creation, manipulation, and printing of complex numbers using functions from ``. It shows how to initialize complex numbers and perform operations like multiplication and trigonometric calculations. ```c #include #include #include void print_complex(const char* note, complex z) { printf("%s %f%+f*i\n", note, creal(z), cimag(z)); } int main(void) { double complex z = -1.0 + 2.0*I; print_complex("z =", z); print_complex("z\u00B2 =", z * z); double complex z2 = ccos(2.0 * carg(z)) + csin(2.0 * carg(z))*I; print_complex("z\u00B2 =", cabs(z) * cabs(z) * z2); } ``` -------------------------------- ### Output of isnormal() Example Source: https://devdocs.io/c/numeric/math/isnormal The output from the `isnormal` example code, illustrating the classification of different floating-point values. ```text isnormal(NAN) = 0 isnormal(INFINITY) = 0 isnormal(0.0) = 0 isnormal(DBL_MIN/2.0) = 0 isnormal(1.0) = 1 ``` -------------------------------- ### Dynamic memory reallocation example Source: https://devdocs.io/c/memory/realloc Demonstrates how to use `realloc` to resize a memory block. It shows initial allocation with `malloc`, followed by multiple `realloc` calls to change the size, and includes error handling and freeing memory. ```c #include #include #include #include void print_storage_info(const int* next, const int* prev, int ints) { if (next) printf("%s location: %p. Size: %d ints (%ld bytes).\n", (next != prev ? "New" : "Old"), (void*)next, ints, ints * sizeof(int)); else printf("Allocation failed.\n"); } int main(void) { const int pattern[] = {1, 2, 3, 4, 5, 6, 7, 8}; const int pattern_size = sizeof pattern / sizeof(int); int *next = NULL, *prev = NULL; if ((next = (int*)malloc(pattern_size * sizeof *next))) // allocates an array { memcpy(next, pattern, sizeof pattern); // fills the array print_storage_info(next, prev, pattern_size); } else return EXIT_FAILURE; // Reallocate in cycle using the following values as a new storage size. const int realloc_size[] = {10, 12, 512, 32768, 65536, 32768}; for (int i = 0; i != sizeof realloc_size / sizeof(int); ++i) { if ((next = (int*)realloc(prev = next, realloc_size[i] * sizeof(int)))) { print_storage_info(next, prev, realloc_size[i]); assert(!memcmp(next, pattern, sizeof pattern)); // is pattern held } else // if realloc failed, the original pointer needs to be freed { free(prev); return EXIT_FAILURE; } } free(next); // finally, frees the storage return EXIT_SUCCESS; } ``` -------------------------------- ### Possible Output of putwchar Example Source: https://devdocs.io/c/io/putwchar The expected output when the provided putwchar example code is executed successfully. ```text ∀∀ ``` -------------------------------- ### C isdigit Example Output Source: https://devdocs.io/c/string/byte/isdigit The expected output when running the provided C example code for the isdigit function. ```text 0123456789 ``` -------------------------------- ### Possible Output of isalnum Example Source: https://devdocs.io/c/string/byte/isalnum This snippet shows the possible output when running the isalnum example with different locales. ```text isalnum('\xdf') in default C locale returned 0 isalnum('\xdf') in ISO-8859-1 locale returned 1 ``` -------------------------------- ### Example Usage of tmpfile Source: https://devdocs.io/c/io/tmpfile Demonstrates creating a temporary file with tmpfile, writing to it, rewinding, reading back, and optionally displaying the file name on Linux. ```c #define _POSIX_C_SOURCE 200112L #include #include int main(void) { printf("TMP_MAX = %d, FOPEN_MAX = %d\n", TMP_MAX, FOPEN_MAX); FILE* tmpf = tmpfile(); fputs("Hello, world", tmpf); rewind(tmpf); char buf[6]; fgets(buf, sizeof buf, tmpf); printf("got back from the file: '%s'\n", buf); // Linux-specific method to display the tmpfile name char fname[FILENAME_MAX], link[FILENAME_MAX] = {0}; sprintf(fname, "/proc/self/fd/%d", fileno(tmpf)); if (readlink(fname, link, sizeof link - 1) > 0) printf("File name: %s\n", link); } ``` -------------------------------- ### Scalar Initialization Examples Source: https://devdocs.io/c/language/scalar_initialization Demonstrates various ways to initialize scalar types including booleans, doubles, integers, pointers, and enumerations. Shows optional braces and non-constant expressions for automatic variables. ```c #include int main(void) { bool b = true; const double d = 3.14; int k = 3.15; // conversion from double to int int n = {12}, // optional braces *p = &n, // non-constant expression OK for automatic variable (*fp)(void) = main; enum {RED, BLUE} e = RED; // enumerations are scalar types as well } ``` -------------------------------- ### Possible output of getchar() example Source: https://devdocs.io/c/io/getchar Example output when the `getchar` demonstration program is run and receives 'abcde' as input. ```text abcde End of file reached ``` -------------------------------- ### C offsetof example Source: https://devdocs.io/c/types/offsetof This example demonstrates how to use the offsetof macro to find the byte offsets of members within a structure. ```c #include #include struct S { char c; double d; }; int main(void) { printf("the first element is at offset %zu\n", offsetof(struct S, c)); printf("the double is at offset %zu\n", offsetof(struct S, d)); } ``` -------------------------------- ### Registering functions for quick program termination Source: https://devdocs.io/c/program/at_quick_exit This example demonstrates how to register two functions, `f1` and `f2`, using `at_quick_exit`. When `quick_exit(0)` is called, these functions are executed in the reverse order of their registration. The output shows that `f2` is called first, followed by `f1`, illustrating the LIFO (Last-In, First-Out) behavior. ```c #include #include void f1(void) { puts("pushed first"); fflush(stdout); } void f2(void) { puts("pushed second"); } int main(void) { at_quick_exit(f1); at_quick_exit(f2); quick_exit(0); } ``` -------------------------------- ### Example Output for char32_t Usage Source: https://devdocs.io/c/string/multibyte/char32_t This is the possible output when running the example code that demonstrates the usage of char32_t with a UTF-32 string. ```text 5 UTF-32 code units: [ 0x7a 0xdf 0x6c34 0x1f34c 0 ] ``` -------------------------------- ### Example Output for UTF-16 String Source: https://devdocs.io/c/string/multibyte/char16_t Shows the possible output when printing the UTF-16 code units of the example string literal. ```text 6 UTF-16 code units: [ 0x7a 0xdf 0x6c34 0xd83c 0xdf4c 0 ] ``` -------------------------------- ### C Initialization Syntax Source: https://devdocs.io/c/language/initialization Demonstrates the basic syntax for initializing objects in C using assignment or brace-enclosed lists. Supports empty initialization for C23. ```c #define directive #elif directive #else directive #endif directive #if directive #ifdef directive #ifndef directive #include directive #line directive #pragma directive ``` ```c _Alignas _Alignas _Alignof operator _Alignof operator _Noreturn (since C23) _Noreturn function specifier ``` ```c alignas (since C23) alignas (since C23) ``` ```c =` expression ``` ```c =` { initializer-list } ``` ```c =` { } (since C23) ``` ```c initializer-list is a non-empty comma-separated list of initializer s (with an optional trailing comma), where each initializer has one of three possible forms: expression { initializer-list } { } (since C23) ``` ```c designator-list = initializer (since C99) where designator-list is a list of either array designators of the form [ constant-expression ] or struct/union member designators of the form . identifier ``` ```c (`type`) { initializer-list } (since C99) ``` ```c (`type`) { } (since C23) ``` -------------------------------- ### C clearerr Example Source: https://devdocs.io/c/io/clearerr This example demonstrates how to use `clearerr` to reset the EOF indicator for a file stream after reading its content. ```c #include #include int main(void) { FILE* tmpf = tmpfile(); fputs("cppreference.com\n", tmpf); rewind(tmpf); for (int ch; (ch = fgetc(tmpf)) != EOF; putchar(ch)) { } assert(feof(tmpf)); // the loop is expected to terminate by EOF puts("End of file reached"); clearerr(tmpf); // clear EOF puts(feof(tmpf) ? "EOF indicator set" : "EOF indicator cleared"); } ``` -------------------------------- ### C Implementation File Example (flib.c) Source: https://devdocs.io/c/language/storage_duration This C source file provides definitions for functions and variables declared in 'flib.h'. It includes static definitions for internal linkage and definitions for external linkage that are used by other translation units. ```c #include "flib.h" static void local_f(int s) {} // definition with internal linkage (only used in this file) static int local_state; // definition with internal linkage (only used in this file) int state; // definition with external linkage (used by main.c) void f(void) { local_f(state); } // definition with external linkage (used by main.c) ``` -------------------------------- ### C while loop examples Source: https://devdocs.io/c/language/while Demonstrates basic usage of the while loop for array initialization and iteration, and a classic implementation of strcpy. ```c #include #include #include enum { SIZE = 8 }; int main(void) { // trivial example int array[SIZE], n = 0; while(n < SIZE) array[n++] = rand() % 2; puts("Array filled!"); n = 0; while(n < SIZE) printf("%d ", array[n++]); printf("\n"); // classic strcpy() implementation // (copies a null-terminated string from src to dst) char src[] = "Hello, world", dst[sizeof src], *p = dst, *q = src; while((*p++ = *q++)) // double parentheses (that are not strictly necessary) // used to suppress warnings, ensuring that this is an // assignment (as opposed to a comparison) by intention, // whose result is used as a truth value ; // null statement puts(dst); } ```