Skip to content

Instantly share code, notes, and snippets.

@dlOuOlb
Last active January 1, 2024 06:10
Show Gist options
  • Save dlOuOlb/e1722a29fbf0426e8ee21cd3717470f9 to your computer and use it in GitHub Desktop.
Save dlOuOlb/e1722a29fbf0426e8ee21cd3717470f9 to your computer and use it in GitHub Desktop.
The C main function with read-only string arguments.

Summary

flowchart TB
	Old.Count("signed int")
	Old.Array("char **")

	Old.Count --> New.Count
	Old.Array -- "undefined behavior" --> New.Array

	subgraph Old.Main["main"]
		New.Count("size_t")
		New.Array("const char *const *")

		New.Count & New.Array --> New.Main["Main"] --> New.State

		New.State("bool")
		New.State -..- New.State.Success(["true"])
		New.State -..- New.State.Failure(["false"])
	end

	New.State.Success --> Old.State.Success(["EXIT_SUCCESS"]) -..- Old.State
	New.State.Failure --> Old.State.Failure(["EXIT_FAILURE"]) -..- Old.State
	Old.State("signed int")
Loading
#if !__STDC__ || !__STDC_HOSTED__ || __STDC_VERSION__ < 202311L
# error "This code requires a standard-conforming C23 compiler with a hosted implementation."
#else
# include <stdlib.h> /* EXIT_(FAILURE|SUCCESS)|size_t */
extern bool Main( size_t C, const char *const[ static true + C ] );
static_assert( alignof( const char * ) == alignof( char * ) );
static_assert( sizeof( const char * ) == sizeof( char * ) );
extern signed int main( signed int argc, char **const argv )
{
auto const void *const hack = argv;
auto const char *const ( *const ArgV )[ ++argc ] = hack; // undefined behavior
auto size_t ArgC = sizeof *ArgV / sizeof **ArgV;
while( argc-- )
while( argc[ argv ] != argc[ *ArgV ] )
return EXIT_FAILURE;
return Main( --ArgC, *ArgV )? EXIT_SUCCESS: EXIT_FAILURE;
}
#endif
#if !__STDC__ || !__STDC_HOSTED__ || __STDC_VERSION__ < 202311L
# error "This code requires a standard-conforming C23 compiler with a hosted implementation."
#else
# include <stdio.h> /* perror|printf|size_t */
extern bool Main( const size_t Count, const char *const Array[ const static true + Count ] )
{
for( auto size_t Index = { }; Index ^ Count; ++Index )
while( 0 > printf( "- \"%s\"\n", Array[ Index ] ) )
return perror( "printf" ), false; // on failure
return true; // on success
}
#endif
@dlOuOlb
Copy link
Author

dlOuOlb commented Oct 18, 2022

Tab-Size Preference: { default, 2, 3, 4, 6, 8 }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment