Evan Martin (evan) wrote in evan_tech,
Evan Martin

do my research / C++ black magic

I have a C/architecture question for y'all.

As of today I'm going to start on some work on Cyclone. (Here's the manual, if you're curious.)

Apparently the C standard doesn't require all pointer types to be interchangable-- that is to say, you can't cast from int* to char* and back and be guaranteed you're ok. void* is instead used as the "superpointer" type, where you can cast anything to void* and back and be ok, and that's why you make generic data types work with void*s.

So my question is: can you name a system where the difference between pointer types actually exists? How about function pointers? Are they also always the same size? (For example, you could imagine a system where code and data were somehow represented by differently-sized pointers-- does such a system exist?)

Speaking of varying-sized pointers, here's some more wacko code, this time in C++.

#include <stdio.h>

class C {
  virtual void f(void) { }

class D : public C {
  virtual void f(void) {
    printf("i am a D!\n");

void main(void) {
  printf("%d\n", sizeof(&C::f));

  void (C::*ourptr)() = &C::f;

  D* d = new D;
  C *creallyd = d;

(First, isn't C++ function pointer syntax even uglier than C? Man, that's some ugly-looking syntax.)

But the bonus question: What does this print?

If you know that first printf prints 8, not 4, you'll probably be able to figure out that ourptr somehow magically carries around information about vtable of C and manages to actually call the printing version of D.

Thankfully, Cyclone only deals with C, so I don't have to worry about that. :)

  • Post a new comment


    default userpic
    When you submit the form an invisible reCAPTCHA check will be performed.
    You must follow the Privacy Policy and Google Terms of use.