c - 重新类型转换一个变量,可能吗?

标签 c gcc casting

是否可以永久地重铸 a 变量,或者有一个包装函数使变量的行为像另一种类型?

我想实现我在另一个问题中发布的内容: Typecasting variable with another typedef

更新:添加了 GCC 作为编译器。可能有一个有用的扩展?

最佳答案

是的,您可以将变量从一种类型转换为另一种类型:

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

但是,您不能就地修改标识符“x”的类型,如果这是您所要求的。不过,接近于此,您可以引入另一个作用域,该作用域使用某种新类型重新声明该标识符:

  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.

你可以做的另一件事是:

  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

关于c - 重新类型转换一个变量,可能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6619580/

相关文章:

c++ - 构建 Boost 系统库失败

java - 将对象降级为未知类

c# - C# 中的 TryGetValue 不适用于字符串,是吗?

C - 如何更改 Ncurses 中的字体大小?

linux - 堆栈粉碎代码在 Linux 内核 2.6.38.7 上不起作用...请帮忙

c - 如何使用 C 绘制 RGB HBITMAP 并将其显示在静态窗口中?

c - 复合文字如何在此代码中工作?

c++ - NULL 指针与 static_cast 的兼容性

c - 在字符串 inC 中搜索空格

c - 错误: ‘node’ undeclared (first use in this function)