簡體   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