Skip to content

Instantly share code, notes, and snippets.

@nil-ableton
Last active August 29, 2015 14:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nil-ableton/70ba28f4b40d4323ca4b to your computer and use it in GitHub Desktop.
Save nil-ableton/70ba28f4b40d4323ca4b to your computer and use it in GitHub Desktop.
void* is special in C, C99, C11
/**
* Local Variables:
* compile-command: "cc -Wall -Weverything -std=c11 voidstar.c -o ./voidstar && ./voidstar"
* End:
*/
#include <stdio.h> // for printf
enum WorkType
{
WT_INT,
WT_LSTRING,
};
// prototype (just to satisfy the absurd -Weverything)
void do_work(int work_type, void* work_data);
// implementation
void do_work(int work_type, void* work_data)
{
switch(work_type)
{
case WT_INT: {
// demonstrates void* is casted automatically to `int*`
int* pointer_to_int = work_data;
printf("got an int: %d\n", *pointer_to_int);
} break;
case WT_LSTRING: {
// demonstrates void* is casted automatically to `char const*`
char const* pointer_to_litteral = work_data;
printf("got a litteral string: %s\n", pointer_to_litteral);
} break;
}
}
int main()
{
int a_serious_integer = 42;
do_work(WT_INT, &a_serious_integer);
do_work(WT_LSTRING, "this is a literal string");
}
@gck-ableton
Copy link

Yeah, I mixed this with the __attribute((malloc)) thing, which is used for aliasing optimization.

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