سؤال

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

هل كانت مفيدة؟

المحلول 3

apparently just take the flag that the compiler gives you and slap a "no" in front of it does the trick!

-Wno-int-to-void-pointer-cast

نصائح أخرى

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);

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;

In some cases doing this would be desired (eg. for the last pointer parameter of glVertexAttribPointer in OpenGL). You should be able to avoid the warning by doing something like this:

#define BUFFER_OFFSET(i) ((char*)NULL+(i))
myFunction(BUFFER_OFFSET(3));

The warning is telling you that ints are narrower than pointers, so you are losing information when you cast from a pointer to an int. As suggested above, use uintptr_t. That is an integer type that is as wide as a pointer. If you are forced to use int, then you are SOL. "Generic" == broken.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top