Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

do you have to declare functions in C? [duplicate]

Tags:

c

Possible Duplicate:
Must declare function prototype in C?

I'm learning C and in the book i'm reading this tidbit of code has a statement of void scalarMultiply(int nRows, int nCols, int matrix[nRows][nCols], int scalar);. The program seems to work even if I do not include this line?

    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;

    }
like image 525
steve Avatar asked Feb 22 '11 19:02

steve


1 Answers

If you don't declare a function before it's used the compiler might try to guess the signature of the function, and this could work.

Anyway you could get very weird results if the function the compiler guessed is different from the actual function: for example if you pass a long long as first parameter to scalarMultiply, it won't get converted to an int, and this will result in undefined behavior: most likely you'll corrupt your stack (the function will read parameters in a different way you meant) and everything will blow up.


Look:

#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 );
}

Output will be:

-1, -1
4294967297

Weird, uh?

like image 83
peoro Avatar answered Oct 11 '22 18:10

peoro