Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Should you dereference function pointers?

Name: Anonymous 2009-11-04 19:33

#include <stdio.h>

void func() {
  printf("hello world\n");
}

void (*go)() = func;

int main() {
  go();    // number 1...
  (*go)(); // or number 2
  return 0;
}


Which is correct ANSI C89? GCC accepts both, even in -ansi -pedantic; it outputs hello world twice.

Name: Anonymous 2009-11-06 4:00

>>18
Yeah, you're doing it wrong. It's array + 4, which is nicer than &array[4].

>>21
It's not harmful at all. The vector is required to be contiguous. In fact it's quite normal to do this with vectors of POD, as long as you don't keep the pointer around when you modify the vector (that should be obvious; the spec defines exactly which modifications invalidate pointers if you want more specifics). Typically you should check that the vector is non-empty though, because otherwise the access might be out of bounds. (The compiler optimizes away the dereferencing in return, but it's still technically undefined behaviour because you're dereferencing invalid memory. In some implementations, if you haven't put anything in the vector yet it won't even have allocated any memory, and the pointer could point anywhere!)

http://www.parashift.com/c++-faq-lite/containers.html#faq-34.3

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List