2

Some C compilers can sometimes deduce a casted pointer as still a lvalue, but gcc defaults won't compile it. Instead of having to port (by human-error-prone way)legacy code base to:

p=(int *)p+1 ; /* increment by sizeof(int) */

can gcc be made to allow this code below (even if not technically correct)?

void f() {
    void *p ; /* type to be cast later for size */
    ((int *)p)++ ; /* gcc -c f.c => lvalue required error */ }

Edit: even if technically incorrect, I assume the only programmer intent for such code is for p to remain lvalue and "increment" it, generating same code as my long form, right? (perreal flagged as "lvalue cast")

Edit2: We all agree refactoring to std C is best, but if something like Mateo's -fpermissive worked, it might not catch future programming errors, but hoping initial gcc porting effort will be less faulty... Any other similar suggestions?

in foq
  • 69
  • 4

1 Answers1

1

If you want to clean up your code(remove excessive casts) , you can concentrate the ugly casts inside a macro or, even better, an inlined function. The below fragment only makes use of implicit casts to/from void*

You are ,of course, still responsible for the proper alignment.


#include <stdio.h>

static void *increment(void * p,size_t offset)
{
char *tmp = p;
return tmp+offset;
}

int main(void)
{
void *ptr = "Hell0 world!\n";

ptr = increment( ptr, sizeof(int) );

printf("%s", (char*) ptr);

return 0;
}
wildplasser
  • 43,142
  • 8
  • 66
  • 109