Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make compiler not show int to void pointer cast warnings

I have some code that does lots of casting from int to void* and vice-versa (i don't care if it's ugly. I like having generic stuff)

Example:

typedef struct _List {
    long size;
    long mSize; // Max size
    void** elementArray;
}List;

List l;
...
int i = 2;
l.elementArray[i] = i; // Intentional usage of pointer as integer
// Actual size of pointer does not matter

but when i compile i get a bajillion

 warning: cast to 'void *' from smaller integer type 'int' [-Wint-to-void-pointer-cast]

warnings. Is there a flag to tell gcc to not print this specific warning?

I'm compiling with -Wall, so I'm not sure if i can make this go away that easilly

like image 296
Jean-Luc Nacif Coelho Avatar asked Mar 31 '14 00:03

Jean-Luc Nacif Coelho


2 Answers

For the sake of others who are possibly looking for an answer like me:

If you want to not add an extra compilation flag due to the fact that you might be upcasting an int to a void* accidentally somewhere else, you can use the following snippet to force a cast from an int to a void* where you are sure you want it to happen and then the compiler won't bug you about the cast:

#define INT2VOIDP(i) (void*)(uintptr_t)(i)

Of course be sure to include stdint.h, so then you can do the following:

void *val = INT2VOIDP(5);
like image 125
DanZimm Avatar answered Sep 23 '22 04:09

DanZimm


you might want to use 'size_t'.

For example, if you have int i and void *a,

i = (void *) a; will give you that warning

to avoid this add size_t

i = (void *) (size_t) a;

like image 43
Vasu Avatar answered Sep 22 '22 04:09

Vasu