【问题标题】:C: const or define? What's the difference and why the second report an error?C:常量还是定义?有什么区别,为什么第二个报错?
【发布时间】:2015-07-08 07:43:44
【问题描述】:
#include <stdio.h>
#include <stdlib.h>
#define MAX 15 //line that give problems

int linearSearch(int v[], int MAX, int valore);

int main()
{
    int ris, valore, v[]={1,1,1,1,1,1,1,1,1,12,1,1,1,1,1};
    scanf("%d", &valore);
    ris = linearSearch(v, MAX, valore);
    printf("%d", ris);
    return 0;
}

int linearSearch(int v[], int MAX, int valore)
{
    int i;
    for (i=0;i<MAX;i++)
    {
        if(valore==v[i])
            return i;
    }
    return -1;    
}

为什么这段代码在编译时会报错?如果我用

替换预处理器指令,为什么它会正确运行
const int MAX = 15;

【问题讨论】:

  • 您的参数int MAX, - 想想当预处理器用MAX 替换15 时会发生什么... int 15 ??
  • 你甚至不需要中间参数。

标签: c compiler-errors constants c-preprocessor


【解决方案1】:

宏(大部分)是简单的文本替换,所以:

#define MAX 15 //line that give problems
int linearSearch(int v[], int MAX, int valore);

将被预处理为:

int linearSearch(int v[], int 15, int valore);
                              ^

当然,标识符不能有数值。

【讨论】:

    【解决方案2】:

    在函数声明中

    int linearSearch(int v[], int MAX, int valore);
    

    及其定义

    int linearSearch(int v[], int MAX, int valore)
    {
       //...
    }
    

    标识符MAX表示变量名。

    但是由于宏定义

    #define MAX 15 
    

    函数声明和定义看起来像

    int linearSearch(int v[], int 15, int valore);
    
    int linearSearch(int v[], int 15, int valore)
    {
            int i;
            for (i=0;i<15;i++)
            {
                if(valore==v[i])
                    return i;
            }
            return -1;
    
        }
    

    因为预处理器在程序编译之前将所有MAX 替换为15。

    Macto 定义没有范围。因此最好使用通常的常量声明。如果你愿意写

    const int MAX = 15;
    

    然后在函数声明中这个名字MAX和名字MAX

    int linearSearch(int v[], int MAX, int valore);
    

    有不同的作用域,代码会编译成功。

    请注意,当您定义一个常量时,您指定的类型不必与相应整数文字的类型相同。例如,您可以定义像

    这样的常量
    const unsigned int MAX = 15;
    

    现在比较以下条件的结果,一方面使用上面定义的常量,另一方面使用宏定义。

    const unsigned int MAX = 15;
    
    if ( MAX > -1 ) puts( "MAX is greater than -1" );
    else puts( "MAX is less than -1" );
    

    #define MAX 15
    
    if ( MAX > -1 ) puts( "MAX is greater than -1" );
    else puts( "MAX is less than -1" );
    

    【讨论】:

      猜你喜欢
      • 2020-06-18
      • 2011-05-27
      • 1970-01-01
      • 1970-01-01
      • 2017-03-27
      • 1970-01-01
      • 2011-09-17
      • 1970-01-01
      • 2012-10-22
      相关资源
      最近更新 更多