繁体   English   中英

为什么我不能创建一个名为 pow() 的函数

[英]Why cant I create a function named pow()

这是我的 C 程序:

#include<stdio.h> 

main() { 
  int a,b; 
  int pow(int,int); 
  printf("Enter the values of a and b"); 
  scanf("%d %d",&a,&b); 
  printf("Value of ab is %d",pow(a,b)); 
} 

pow(int c,int d) { 
  return c*d; 
}

我的程序中没有包含 math.h。 我正在使用 gcc 编译器。 我收到以下错误

ex22.c: In function `main': 
ex22.c:6: error: conflicting types for `pow'

搜索后我才知道 math.h 中有一个 pow 函数。 但我不包括 math.h 但我仍然收到错误。 如何 ?

您不应该为自己的函数使用标识符,该标识符也是 C 标准库函数的名称,无论您是否包含该标准函数的标头。 C 标准明确禁止这种情况,除非函数被声明为static ,并且编译器可能会特别处理这些函数(例如在pow(x, 2)的情况下,通过发出x*x代码而不是函数调用)。

这个有效,但有警告:

warning: incompatible redeclaration of library function 'pow' [-Wincompatible-library-redeclaration] int pow (int,int); ^ test.c:3:5: note: 'pow' is a builtin with type 'double (double, double)'

#include<stdio.h>

int pow (int,int);

int main(void) {
    int a,b;
    printf("Enter the values of a and b");
    scanf("%d %d",&a,&b);
    printf("Value of ab is %d", pow(a,b));
}

int pow(int c,int d)
{
    return c*d;
}

试试这个:没有警告但疯狂的编程

#define pow stupidpow
#include<stdio.h>

int main(void) {
    int a,b;
    printf("Enter the values of a and b\n");
    scanf("%d %d",&a,&b);
    printf("Value of ab is %d", pow(a,b));
}

int pow(int c,int d)
{
   // count c^d
   printf("\nAns is \n");
}

使用 PowInt 代替 pow。 这样更安全,而且永远不会引起任何混乱。

int PowInt (const int m, const int e)
{
int i, r;

        r = 1;
        for (i = 1; i <= e; i++)
            r = r * m;
        return( r );    
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM