Error returning lower value

0

I'm trying to return the smallest value using va_args , which supports multiple arguments, but it always returns the same number: -13227;

#include <stdio.h>
#include <limits.h>
#include <stdarg.h>

int minimo(int args, ...) 
{
    int elemento, min;

    va_list valist;
    va_start(valist, args);

    min = INT_MAX;
    for(int i=0; i<args; i++)
    {
        elemento = va_arg(valist, int);
        if(elemento < min)
            min = elemento;
    }

    va_end(valist);

     return min;
}

int main() 
{           
    int num = minimo(8, 5, 3, 7, 12, 6);
    printf("%d\n", num);

    return 0;
}

And if you change the variable min from int to unsigned int , it always returns 0. link

    
asked by anonymous 02.01.2018 / 21:46

3 answers

1

Here it says that min is the highest possible value:

min = INT_MAX;

Then ask

if(min < elemento)

If min is the highest value possible, it will never be the minimum, it will never enter this if .

If you do the opposite, it works:

if (elemento < min)

In addition to this the first argument passed in the function should be the amount of elements that will have to follow, used 8 when in fact only has 5, this takes memory dirt and spoils the comparison.

    
02.01.2018 / 21:55
0

The problem is this line here:

if(min < elemento)

I believe the signal is changed. The block of this if is only executed if min is smaller than the compared element, but min will never be less than anything else since, by definition, its initial value is the largest possible value.

    
02.01.2018 / 21:55
0

2 things.

One is that the signal was changed in if, already said by colleagues, the other is that you supplied 5 numbers, but said that you had 8, so your for loop attempts to access parameters that do not exist.

Call your function so you will have no problems:

minimo(5, 5, 3, 7, 12, 6);
    
02.01.2018 / 22:03