Home > OS >  Why that thing every time skip next element?
Why that thing every time skip next element?

Time:11-21

Hello I want to output every positive element that is even. I use VA_LIST. The compiler counts numbers only from 1 to 4, 4 to 8 is not counted, what is the problem?

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

int MyPerfectF(int num, ...) {
    int sum = 0;
    va_list args;
    va_start(args, num);
    int x;
    while (va_arg(args, int) != NULL) {
        x = va_arg(args, int);
        if (x > 0 && x % 2 == 0) {
            printf("%d ", x);
            sum  ;
        }
    }
    printf("\nAmount of true numbers is: %d", sum);
    va_end(args);
    return 0;
}

int main(void) {
    int num = 5;
    int a, b, c, d;
    scanf_s("%d %d %d %d", &a, &b, &c, &d);
    MyPerfectF(num, a, b, c, d, NULL);
}

CodePudding user response:

From va_arg [emphasis mine]:

T va_arg( va_list ap, T );

The va_arg macro expands to an expression of type T that corresponds to the next parameter from the va_list ap.

In MyPerfectF() function,

    while (va_arg(args, int) != NULL) {
        x = va_arg(args, int);

va_arg is called twice, so if the input contains even number at even place then all those even number will be counted otherwise they are not.

Apart from this there is one more problem in your code - In context of your program, type T is int. Compiler must be throwing a warning on comparison statement (va_arg(args, int) != NULL) of while loop condition.

You don't need to pass NULL to indicate the termination of arguments. Instead, pass the value of num as number of variable arguments passed to MyPerfectF() function, like this:

int main(void) {
    int num = 4;
    .....
    .....
    MyPerfectF(num, a, b, c, d);
}

and in MyPerfectF() replace the while loop with this

for (int i = 0; i < num;   i) {

Also, you can assign the return value of scanf() to num and pass it to MyPerfectF() function, this will ensure that the MyPerfectF() function will read only those arguments which are successfully read and assigned by scanf(). Putting these altogether:

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

int MyPerfectF(int num, ...) {
    int sum = 0;
    va_list args;
    va_start(args, num);

    for (int i = 0; i < num;   i) {
        int x = va_arg(args, int);
        if (x > 0 && x % 2 == 0) {
            printf("%d ", x);
            sum  ;
        }
    }
    va_end(args);
    printf("\nAmount of true numbers is: %d\n", sum);
    return 0;
}

int main(void) {
    int a, b, c, d;
    printf ("Enter 4 values:\n");
    int num = scanf("%d %d %d %d", &a, &b, &c, &d);
    MyPerfectF(num, a, b, c, d);
    return 0;
}
  • Related