How to decide the type of a function?

2

In many C codes I see on the internet, I only see functions of type void and int and can declare functions of other types? For example struct and float .

I made a simple test with the types char and float and it worked, but I still do not understand the true importance of the function type when I should use which?

#include <stdio.h>
#include <stdlib.h>

float rf(){

    float testfloat = 1.3;
    char string['C'];
    printf("'%f' '%s'", testfloat, string);

}

char rc(){

    float testfloat = 1.3;
    char string['C'];
    printf("'%f' '%s'", testfloat, string);

}

int main(){

 rf();
 rc();
 return 0;

}
    
asked by anonymous 23.06.2016 / 00:41

1 answer

4

Actually the function has no type, the type is the value it returns. That is important.

The return, as well as the parameters, variables, constants, etc. can be and should have any type available in the code, can be one already defined in the language, the standard libraries, other libraries that you are using, or types defined by your code (with typedef and probably struct ). >

Obviously the function should return something with the command return and the value returned must be compatible with the return type declared in it.

If it is to return nothing, then the return type must be void . Thus the function can not be used in expressions that always expect some value. void is no value, it is "less" than null.

You should use whatever is best for you to solve the problem. No generic answer can determine which is best suited for the specific situation.

Of course, some things we know. A type must contain all valid values that it knows that element of code can have. For example, if you declare a int , probably (depends on architecture), the highest possible value is 2,147,483,647.

In some rare cases you may need an unsigned type (which only accepts positives), it is rare and not appropriate here because you should not opt for them as a default.

If you need a monetary value the novice programmer goes hot on float or double (which allow values with decimal part), but You can not use them for this .

Anyway, it's just examples, you can not put all the basic rules under penalty of asking the question too broad.

The example slightly improved according to my speculation:

#include <stdio.h>

float rf() {
    float testfloat = 1.3;
    char string['C'];
    printf("'%f' '%s'", testfloat, string);
    return testfloat;
}

char rc() {
    float testfloat = 1.3;
    char string[]; //havia um erro aqui e isso ainda não vai dar certo
    printf("'%f' '%s'", testfloat, string);
    return 'a';
}

void rv() {
    printf("faz algo aqui");
    return;
}
int main() {
    float x = rf();
    char c = rc();
    rv();
    return 0;
}
    
23.06.2016 / 01:21