Methods without parameters and with parameters

5

Declaration methods without parameters:

void exemploDeMetodo(){
    int i;
}

Calling methods without parameters:

exemploDeMetodo();

If I want to do a parameterized method it's like?

Is it like this?

void exemplo(int i){
    faz algo com o i
}

Calling with parameters:

int inteiro = 1;
exemplo(inteiro);

If I want to return an integer, will I have to put a parameter in the method?

    
asked by anonymous 02.11.2014 / 18:18

2 answers

7

You are correct in all your initial assumptions.

To return an integer you do not need any parameters. The feedback works separately. You can have parameter but it has no direct relation to the return. Return is a result that you pass back to who called.

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

int exemplo1() { return 1; }

int exemplo2(int i) { return i * 2; }

int exemplo3() {
    srand(time(0));
    return rand();
}

int exemplo4(int i) { return i > 0 ? 1 : 0; }

int main(void) {
    printf("%i\n", exemplo1());
    printf("%i\n", exemplo2(2));
    printf("%i\n", exemplo3());
    printf("%i\n", exemplo4(2));
}

See running on ideone . And in Coding Ground . Also I put GitHub for future reference .

Note that in C you should always declare the datatype for everything: variables, vector elements, structure fields, parameters, and of course, you can declare the type of functions, which are confused with the return type of the function . void means returning nothing. Of course, int means that it will return an integer.

In C there's even how to return values through parameters, but this is advanced, do not worry about it until you learn other things before. It will still be of no use to you.

    
02.11.2014 / 18:29
4

You have hit most everything, you just lacked the part of returning a value.

A function has the following format:

tipoDeRetorno nomeDoMetodo(tipoDoParametro valorDoParametro) {
    //se o tipoDeRetorno for void não precisa retornar nada
    //caso contrário deve-se usar a seguinte notação:
    return variavelCompativelComOTipoDeRetorno;
}

To do a function that returns a value of integer type you should change the void that you put in your example, like this:

int exemplo(int i) {
    int j = i*2;
    return j;
}

Note that you do not necessarily need to return i , you can return another variable, the result of an expression or a value, as long as it matches the ReturnType.

    
02.11.2014 / 18:30