Very simply, is the following code safe/portable?
#include <stdio.h>
#include <stdlib.h>
int add(int *a, int *b)
{
return *a + *b;
}
int main()
{
int x = 2;
int y = 3;
void *ptr1 = &x;
void *ptr2 = &y;
fprintf(stdout, "%d + %d = %d\n", x, y, add(ptr1, ptr2));
return EXIT_SUCCESS;
}
I've compiled this with -Wall -Werror
and -Wextra
and received no warnings; it seems to run fine.
There's two things to consider:
C allows the implicit conversion from a void pointer to any other object pointer type. So it's syntactically okay to pass those arguments.
The type of the actual object being pointed to, and the type of the pointer the function expects, must satisfy strict aliasing constraints, otherwise your program is in undefined behavior land.
You are okay on both points. So your program is perfectly fine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With