Variadic functions in C

  • + 0 comments
    int sum(int count,...) {
        va_list ptr;
        va_start(ptr, count);
        
        int sum = 0;
        for(int i = 0; i < count; i++) {
            sum += va_arg(ptr, int);
        }
        va_end(ptr);
        return sum;
    }
    
    int min(int count,...) {
        va_list ptr;
        va_start(ptr, count);
        
        int min = MAX_ELEMENT;
        for(int i = 0; i < count; i++) {
            int value = va_arg(ptr, int);
            min = (min > value) ? value : min;
        }
        va_end(ptr);
        return min;    
    }
    
    int max(int count,...) {
        va_list ptr;
        va_start(ptr, count);
        
        int max = MIN_ELEMENT;
        for(int i = 0; i < count; i++) {
            int value = va_arg(ptr, int);
            max = (max < value) ? value : max;
        }
        va_end(ptr);
        return max;
    }