你必须在C中声明函数吗?

ste*_*eve 5 c

可能的重复:
必须在 C 中声明函数原型吗?

我正在学习 C,在我正在阅读的这本书中,这段代码有一个声明void scalarMultiply(int nRows, int nCols, int matrix[nRows][nCols], int scalar);. 即使我不包括这一行,该程序似乎也能工作?

    int main(void)
    {

        void scalarMultiply(int nRows, int nCols, int matrix[nRows][nCols], int scalar);
        void displayMatrix(int nRows, int nCols, int matrix[nRows][nCols]);
    int sampleMatrix[3][5] = {
        { 7, 16, 55, 13, 12},
        { 12, 10, 52, 0, 7 },
        { -2, 1, 2, 4, 9   }

    };

    scalarMultiply(3, 5, sampleMatrix, 2);


}    void scalarMultiply(int nRows, int nCols, int matrix[nRows][nCols], int scalar){
        int row, column;

        for (row = 0; row < nRows; ++row)
            for (column = 0; column < nCols; ++column)
                matrix[row][column] *= scalar;

    }
Run Code Online (Sandbox Code Playgroud)

peo*_*oro 5

如果在使用函数之前没有声明函数,编译器可能会尝试猜测函数的签名,这可能会起作用。

无论如何,如果编译器猜测的函数与实际函数不同,您可能会得到非常奇怪的结果:例如,如果您将 along long作为第一个参数传递给scalarMultiply,它将不会转换为int,这将导致未定义的行为:很可能你会破坏你的堆栈(该函数将以不同的方式读取参数)并且一切都会爆炸。


看:

#include <stdio.h>
int main( ) {
    f( (long long int) -1 );
    g( 1, 1 );
    return 0;
}
void f( int a, int b ) {
    printf( "%d, %d\n", a, b );
}
void g( long long int a ) {
    printf( "%lld\n", a );
}
Run Code Online (Sandbox Code Playgroud)

输出将是:

-1, -1
4294967297
Run Code Online (Sandbox Code Playgroud)

很奇怪吧?


nmi*_*els 0

如果你想在定义之前调用一个函数,你必须声明一个原型。否则,不行。main这就是为什么许多 C 程序都是在底部编写而很少的辅助函数在顶部编写的。编译单元中真正需要函数原型的唯一一次是相互递归。