Questions about C Function Prototypes and Compilation

后端 未结 4 1791
别那么骄傲
别那么骄傲 2020-12-19 11:37

With the following code:

int main(){
    printf(\"%f\\n\",multiply(2));
    return 0;
}

float multiply(float n){
    return n * 2;
}

When

4条回答
  •  天涯浪人
    2020-12-19 11:59

    Question 1: Yes you are correct. If there is no function prototype, the default type is int

    Question 2: When you are compiling this code as one file, the compiler see that there is already function named multiply and it has a different type than supposed (double instead of int). Thus compilation doesn't work.

    When you separate this in two files, the compiler makes two .o files. In the first one it suppose that the multiply() function will be in other file. Then linker links both files into a binary and according to the name multiply inserts call of float multiply() on the place of int multiply() supposed by the compiler in the first .o file.

    Question 3: If you read int 2 as a float, you will get a very small number (~1/2^25), so after that you multiply it by 2 and it still remains too small for format %f. That's why you see 0.00000.

提交回复
热议问题