P.S.- I have taken int and int * for simplicity purpose, It can also be struct and struct *.
I am trying to implement a macro to copy data present in one variable to other independent of the variable datatype, In the below solution I am using '_Generic' compiler feature. program 1:
#include<stdio.h>
#include <string.h>
#define copyVar(var,newVar) _Generic((var),int:({memcpy(newVar,(void *)&var,sizeof(int));}),\
int *:({memcpy(newVar,(void *)var,sizeof(int));}),default:newVar=var)
int main() {
int data = 2;
int *copy;copy = (int *)malloc(sizeof(int));
copyVar(data,copy);
printf("copied Data=%i",*copy);
}
Program 2:
#include<stdio.h>
#include <string.h>
#define copyVar(var,newVar) _Generic((var),int:({memcpy(newVar,(void *)&var,sizeof(int));}),\
int *:({memcpy(newVar,(void *)var,sizeof(int));}),default:newVar=var)
int main() {
int data = 2;
int *copy;copy = (int *)malloc(sizeof(int));
copyVar(&data,copy);
printf("copied Data=%i",*copy);
}
Now problem is, 'program 1' get compiled successfully despite some warning. But while compiling program 2 gcc throwing error:
error: lvalue required as unary '&' operand #define copyVar(var,newVar) _Generic((var),int:({memcpy(newVar,(void *)&var,sizeof(int));}),
and I assume this is due to since _Generic int: selection get preprocessed with one more ampersand
(void *)&&var
why is gcc evaluates all selection?
copyVar
macro. It's very hard to read. – user694733struct S *a, *b
), you can simply do*a = *b;
. – user694733a = b
would copy address (typestruct S *
) fromb
toa
. By dereferencing pointer with*
you get access to pointee. Thus*a = *b
copies the typestruct S
, from address pointed byb
to address pointed bya
. – user694733