You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesión a prueba de IA

Antes: $249

Currency
$209
Suscríbete

Termina en:

0 Días
5 Hrs
18 Min
9 Seg

Tipos de retorno en funciones

4/12
Resources

What are function types according to their return value?

Let's start by analyzing how we categorize functions in C according to their return value. This is a fundamental distinction that will allow you to understand how and when to use each type of function. In C, functions can be classified into four types, depending on whether or not they have arguments and whether or not they return a value. Let's look at each in detail.

How do functions with no arguments and no return value work?

Functions with no arguments and no return value are defined using the void type. This indicates that the function does not return any data when executed. These functions are declared as follows:

void functionName();

And they are called by simply placing their name followed by parentheses and a semicolon:

functionName();

Ideally, this type of functions are useful in embedded systems or when working with hardware where, for example, you need to execute an action (such as moving a robot) without requiring a return value.

What are functions with arguments but no return value?

In this case, functions take one or more arguments that you can pass when called, but still do not return a value, still using void. They are defined as follows:

void functionName(dataType arg1, dataType arg2);

These functions are practical when you need to operate on data provided when calling the function, but where the result does not need to be returned. Such is the case in hardware control applications, where an action is performed depending on the arguments.

What about functions without arguments but which return a value?

These functions are defined by indicating the type of data to be returned instead of void. Although they receive no arguments, they return information that can be used later. They are declared as follows:

dataType functionName();

The benefit of this type of function is that it can generate or calculate a value inside its body and return it to be used elsewhere in the code.

What are the characteristics of functions with arguments and with return value?

Finally, functions that both take arguments and return a value are extremely useful. They allow complex operations that take input data, process it, and return a new result. Their declaration is as follows:

dataType functionName(dataType arg1);

These functions are highly versatile, allowing a more manageable flow of data between different parts of your program, ensuring that operations are correctly parameterized and their results well defined.

How to correctly apply the function types?

The correct use of each function type will always depend on the context and requirements of the problem you are solving. Remember that:

  • Void functions: They are effective for actions involving direct execution without return, common in hardware control.
  • Functions that return values: Ideal for processes that require results of operations, economy of resources and reuse.
  • Functions with and without arguments: They will depend on the need for input data to perform specific actions.

The secret lies in planning in advance what you need to achieve with each function, evaluating your data processing and return needs to optimize your C programs and ensure efficiency and clarity in their execution.

Contributions 18

Questions 2

Sort by:

Want to see more contributions, questions and answers from the community?

Tipos de retorno en funciones 😄

<1. Funciones sin argumentos y sin valor de retorno

void functionName(); //Declarando la function.
functionName(); //Invocando o ejecutando a la function
void functionName()// definicion de la function
{
  //logica
}

2. Funciones con argumentos, pero sin valor de retorno

void functionName(float); //Declarando la function.
functionName(float); //Invocando o ejecutando a la function
void functionName(float) // definicion de la function
{
  //logica
}

3. Funciones sin argumentos, pero con valor de retorno

int functionName();

4. Funciones que tienen argumentos y valor de retorno

int functionName(int, float);
>

También es posible declarar e inicializar la función directamente, por ejemplo el código de la clase anterior quedaría así:

#include <stdio.h>


int integersPower(int base, int exp){
    int i,p;
    p=1;
    for(i=1; i<=exp; i++){
        p *= base;
    }
    return p;
}

int main()
{
    int i;
    for(i=0; i<10; i++){
        printf("exp = %d, result = %d \n", i, integersPower(2,i));
    }

    return 0;
}


Me parece más cómodo y te ahorras una línea de código, no sé si tendrá algún inconveniente

Sugerencia @equipoPlatzi utilizar una guía de estilo para poder escribir todos unos programas que sean legibles fácilmente independientemente de quien los escriba.

¿Por que se usa int main() para definir la función principal y no void main()?

caso de uso donde la función no necesita que devuelva nada

  • Una función que imprime por la salida estándar una letra. (En este caso la salida estándar es la pantalla)
#include <unistd.h>

void	putchar(char a)
{
	write(1, &a, 1);
}

De hecho en las funciones que no tienen argumentos y que no regresan nada las podemos declarar de la siguiente manera:

void functionName(void);

Tipos de retorno de funciones

Ya vimos lo que son las funciones, ahora toca ver que tipos de retorno pueden tener cada una. Para esto tenemos 4 tipos:

  1. Función sin argumentos y sin valor de retorno: Este tipo de función suele ser usada por menus o para manipular micro controladores
void functionName(); //Declarando la function.

functionName(); //Invocando o ejecutando a la function

void functionName()// definicion de la function
{
  //logica o statments
}
  1. Función con argumentos, pero sin valor de retorno: Este tipo de función suele ser usada para realizar calculos y no devolver algun valor, etc.
void functionName(float); //Declarando la function.

functionName(float); //Invocando o ejecutando a la function

void functionName(float) // definicion de la function
{
  //logica o statments
}
  1. Función sin argumentos, pero con valor de retorno: Este tipo de función puede ser usada para enviar un mensaje o valor.
int functionName(); //Declarando la function.

functionName(); //Invocando o ejecutando a la function

int functionName() // definicion de la function
{
  //logica
}
  1. Función con argumentos y con valor de retorno: Este tipo de función es la mas usada y es usada normalmente para tratar los datos.
int functionName(int); //Declarando la function.

functionName(dato); //Invocando o ejecutando a la function

int functionName(int dato) // definicion de la function
{
  //logica
}

De hecho hasta este punto del curso la mayoría de las funciones que he usado son de tipo void sin retorno, con y sin argumentos, y las otras funciones con retorno que he usado son solamente las que he visto en esta clase y en el curso de Programación Estructurada para la función de los factoriales.

Hola a todos, he creado una funcion que encuentra la raiz cuadrada exacta de un numero, este es el codigo:

int raiz_cuadrada_exacta(int numero)
{
    int i=1;
    while(i< numero)
    {
        if (i*i == numero)
        {
            return i;
        }
        else 
        {
            i += 1;
            continue;
        } 
    }
}
int main()
{
    printf("%d", raiz_cuadrada_exacta(144));
}
No se si hablan mas adelante pero falto explicar el tipo de funcion booleana para determinar que un valor sea verdadero o falso en caso de que necesites cambiarlo

Ejemplo de uso de una función Void para recibir los parámetros de la función de potencia:

#include <stdio.h>
int nExponent (int base, int n);
void parametros();
int b;
int exponenteee;

int main(){
    parametros();
    for (int i = 1; i <= exponenteee; i++) {
        printf("\nn=%d resultado de la potencia= %d", i, nExponent(b,i));
    }
    

    return 0;
}

int nExponent (int base, int n){
    int r=1;
    for (int k = 0; k < n; k++){
        r=r*base;
    }
    return r;
}

void parametros(){
    printf("ingrese el la base: ");
    scanf("%d", &b);
    printf("\ningrese el exponente: ");
    scanf("%d", &exponenteee);
}

Buena clase

Van a haber cuatro tipos de funciones, dos de las cuales no van a retornar ningún tipo de valor, pero pueden tener argumentos o no.
Las otras dos funciones van a retornar u valor de salida, pero pueden tener o no argumentos de entrada.

Segun he visto en otros cursos, cuando tienes functionName(); tambien se le conoce como prototipo y se escribe ante de la funcion main.

Sintaxis de una función
/*
tipoRetorno nombreFuncion(param1, param2, … paramN) {
// sentences
}
*/

Con el paso de parámetros, estamos viendo como diversas partes del programa se comunican entre sí:
-funciones que no reciben argumentos ni
retornan valores
-funciones que reciben argumentos, pero
que no retornan valores
-funciones que reciben argumentos, y
retornan valores
-programas que llaman a otros programas sin paso de argumentos
-programas que llaman a otros programas , con paso de argumentos(usando sockets).

Cuando una función no retorna nada, se define void, cuando no recibe argumentos también sería void.

void miFuncion (void)
{
	sentencia_1;
	sentencia_n;
}

buena clase