开发者

Re-typecasting a variable, possible?

Is it possible to recast the a variable permanently, or have a wrapper function such that the variable would behave like another type?

I would want t开发者_JS百科o achieve something I posted in the other question: Typecasting variable with another typedef

Update: Added GCC as compiler. May have a extension that would help?


Yes, you can cast a variable from one type to another:

 int x = 5;
 double y = (double) x; // <== this is what a cast looks like

However, you cannot modify the type of the identifier 'x' in-place, if that is what you are asking. Close to that, though, you can introduce another scope with that identifier redeclared with some new type:

  int x = 5;
  double y = (double) x;
  {
      double x = y; // NOTE: this isn't the same as the 'x' identifier above
      // ...
  }
  // NOTE: the symbol 'x' reverts to its previous meaning here.

Another thing you could do, though it is really a horrible, horrible idea is:

  int x = 5;
  double new_version_of_x = (double) x;  // Let's make 'x' mean this
  #define x new_version_of_x
  // The line above is pure evil, don't actually do it, but yes,
  // all lines after this one will think 'x' has type double instead
  // of int, because the text 'x' has been rewritten to refer to
  // 'new_version_of_x'. This will likely lead to all sorts of havoc


You accomplish that by casting then assigning.

int f(void * p) {
  int * i;

  i = (int *)p;

  //lots of code here with the i pointer, and every line
  //really thinks that it is an int pointer and will treat it as such
} 

EDIT From the other question you linked:

typedef struct {
  unsigned char a;
  unsigned char b; 
  unsigned char c;
} type_a;

typedef struct {
 unsigned char e;
 unsigned char f[2];
} type_b;

//initialize type a
type_a sample;
sample.a = 1;
sample.b = 2;
sample.c = 3;

Now sample is initialized, but you want to access it differently, you want to pretend that in fact that variable has another type, so you declare a pointer to the type you want to "disguise" sample as:

type_b * not_really_b;
not_really_b = (type_b*)&sample;

See, that is the whole magic.

not_really_b->e is equal 1

not_really_b->f[0] is equal 2

not_really_b->f[1] is equal 3

Does this answer your question?


The other answers are better (declare a variable of the type you want, and do an assignment). If that's not what you're asking for, you could use a macro:

long i;
#define i_as_int ((int)i)

printf( "i = %ld\n", i);
printf( "i = %d\n", i_as_int);

But wouldn't it be clearer to just say (int) i if that's what you mean?


As long as you realize in C pointers are nothing but addresses of memory 
locations of certain types, you should have your answer. For example the
following program will print the name of the file

int main(int argc, char *argv[]) {
    int *i;
    i = (int *) argv[0];
    printf("%s\n", argv[0]);
    printf("%s\n", ((char *) i));
}

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜