C code portability

I have the following code

int main() { int a=6; void *p; p=&a; p++; } 

Does the void pointer point to a specific value (if it holds the address of any data type)?

In the above case, p incremented by 1, even if it indicates an integer value. In my opinion, the above code causes the Implementation Defined behavior.

+4
source share
3 answers

The code is invalid from standard point C. It is not permissible to increment void * pointers or any other pointers to incomplete types.

Your compiler implements it as an extension, which, of course, is not portable.

+7
source

Applying the ++ operator to void* is a GCC extension that, as I was told, makes some things more convenient for very low-level programming (and you don’t need to throw so much, basically). I do not think that I have ever encountered a situation where I seriously do not want to throw on unsigned char* .

Use the -pedantic flag if you are writing code that should be portable.

+5
source

Besides the answer of AndreyT :

Take a look at stdint.h , which makes your code more portable.

+1
source

Source: https://habr.com/ru/post/1303787/


All Articles