Skip to content

Instantly share code, notes, and snippets.

@nil-ableton
Last active Aug 29, 2015
Embed
What would you like to do?
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

gck-ableton commented Jun 8, 2015

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