I'm reading the book Head First C and I am the part about the variable arguments.
I wrote the following code:
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
enum drink {
MUDSLIDE, FUZZY_NAVEL, MONKEY_GLAND, ZOMBIE
};
double price(enum drink d) {
switch(d) {
case MUDSLIDE:
return 6.79;
case FUZZY_NAVEL:
return 5.31;
case MONKEY_GLAND:
return 4.82;
case ZOMBIE:
return 5.89;
}
return 0;
}
double calc(int args, ...) {
double total = 0;
va_list ap;
va_start(ap, args);
int i;
for (i = 0; i < args; i++) {
int currentDrink = va_arg(ap, int);
total += price((drink) currentDrink);
}
va_end(ap);
return total;
}
int main() {
printf("Price is %.2f\n", calc(2, MONKEY_GLAND, MUDSLIDE));
return 0;
}
The code compiles and works perfectly.
But... There are two different lines of my solution with the book.
My:
int currentDrink = va_arg(ap, int);
total += price((drink) currentDrink);
Book:
enum drink currentDrink = va_arg(ap, enum drink);
total += price(currentDrink);
I tried to use the solution proposed in the book, but the error during execution and reports a warning: 'drink' is promoted to 'int' when passed through '...'
The book is used gcc compiler on linux. I am using gcc on Windows.
Question: What is the reason I was unable to compile the code proposed in the book?
Edit There configured wrong. Was using a C++ compiler was thinking of using a C. But the question remains: why in C++ results in a warning and error in the execution?
gcc --version.typedef enum drink { MUDSLIDE, FUZZY_NAVEL, MONKEY_GLAND, ZOMBIE } drink;. That way, you can just usedrinkas a type, rather than having to typeenum drink.