【问题标题】:Strange error with #define in cc中#define的奇怪错误
【发布时间】:2011-07-15 08:12:51
【问题描述】:

我知道 #define 在编译为实际值之前被替换。那么为什么这里的第一个代码编译没有错误,而第二个没有?

第一个;

#include <stdio.h>
#include <stdlib.h>
int main()
{
   printf("bc");
   return 0;
}

第二个(不工作);

#include <stdio.h>
#include <stdlib.h>
#define Str "bc";
int main()
{
   printf(Str);
   return 0;
}

error: expected ')' before ';' token

谢谢你的回答,对不起我的英语不好......

【问题讨论】:

  • 你确定第一个正在编译吗?该错误看起来是因为在您的第一个示例中"bc" 之后的;
  • 谢谢你,我的错,我替换了两个代码块
  • 谢谢大家,我忘记分号了。

标签: c compiler-errors printf c-preprocessor


【解决方案1】:

因为Str 宏的计算结果为"bc"; - 包含分号。所以你的宏扩展为:

printf("bc";);

您不需要在#define 后面加上分号。它们以换行符结束,而不是像 C 语句那样以分号结束。我知道,这很令人困惑; C 预处理器是一头奇怪的野兽,在人们了解之前就被发明了。

【讨论】:

    【解决方案2】:

    实际上第二个有效,第一个无效。问题是分号:

    #define Str "bc";
                    ^
    

    【讨论】:

      【解决方案3】:

      使用

      #define Str "bc"
      

      替换后的定义如下:

      printf("bc";);
      

      【讨论】:

        【解决方案4】:

        第一个问题是Str"bc";替换了。

        改成

        #define Str "bc"
        

        【讨论】:

          【解决方案5】:

          您需要删除 ;你在哪里定义 str。因为你会得到 printf("bc";);

          【讨论】:

            【解决方案6】:

            第一个代码无法编译,因为您需要在#define 之后删除分号,第二个代码可以正常工作。

            【讨论】:

              【解决方案7】:

              第一个不起作用,因为这些行:

              #define Str "bc";
              printf(Str);
              

              扩展到这一行:

              printf("bc";);
              

              你想要:

              #define Str "bc"
              

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 2013-02-08
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2011-05-13
                • 2011-11-13
                相关资源
                最近更新 更多