【问题标题】:Conversion of datatype through macro in C通过C中的宏转换数据类型
【发布时间】:2012-08-09 07:42:21
【问题描述】:
#include <stdio.h>
#include <ctype.h>
#define int long
int main ()
{
  char c;
  int i=0;
  char str[]="Example sentence to test isspace\n";
  while (str[i])
  {
    c=str[i];
    if (isspace(c)) c='\n';
    putchar (c);
    i++;
  }
  return 0;
}

在linux环境下会报错,因为: isspace 将扩展为

if (((*__ctype_b_loc ())[(int) ((c))] & (unsigned short int) _ISspace)) c='\n';

当我通过宏将 int 更改为 long 时,它将变为

if (((*__ctype_b_loc ())[(long) ((c))] & (unsigned short long) _ISspace)) c='\n';

因此会引发错误,请提供答案。

【问题讨论】:

  • 定义一个匹配任何 C 保留字的宏会导致未定义的行为。所以不要那样做。
  • 如果您告诉我们编译器 (?) 给您的错误,我们或许可以帮助您解决真正的问题。使用平台定义的类型或宏进行调和肯定不是一个有效的解决方案

标签: c types macros


【解决方案1】:

简单的答案:不要用宏将 int 更改为 long。

如果你真的必须这样做,你可以这样做:

#include <stdio.h>
#include <ctype.h>
#define int long
int main ()
{
  char c;
  int i=0;
  char str[]="Example sentence to test isspace\n";
  while (str[i])
  {
    c=str[i];
#define int int
    if (isspace(c)) c='\n';
#define int long
    putchar (c);
    i++;
  }
  return 0;
}

【讨论】:

  • 即使这仍然是可怕的。为什么不直接使用 isspace 所期望的 int 呢?
  • @user931794 - 我同意,但也许系统中还有其他需要定义的东西,所以这至少可以工作。
  • 嗨,我按照你的建议做了同样的事情,非常感谢,
  • @ranganath111 - 我的第一个也是唯一的建议是不要使用#define int long - 这是你应该做的。
【解决方案2】:
#define int long

这是一个非常糟糕的主意。不要这样做。

linux 环境报错

不,它没有。用 gcc 编译和执行就好了。

当我通过宏将 int 更改为 long 时

这是一个非常糟糕的主意。不要这样做。

你的问题的答案是:如果你试图用宏重新发明 C 语言,那么坏事就会发生,你只能靠自己来解决它们。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-17
    • 2017-10-14
    • 2014-05-25
    • 1970-01-01
    • 1970-01-01
    • 2020-10-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多