Reputation: 672
I have a question. I have line in my program:
sprintf(buff,"Nieznany znak: %d",(char)va_arg(x, const char)); break;
Why after compile I have an error:
error.c: In function 'error':
error.c:30:46: warning: 'char' is promoted to 'int' when passed through '...' [e
nabled by default]
case 0xfe: sprintf(buff,"Nieznany znak: %d",(char)va_arg(x, const char)); brea
k;
^
error.c:30:46: note: (so you should pass 'int' not 'char' to 'va_arg')
error.c:30:46: note: if this code is reached, the program will abort
In my opinion everything is okay, why I can't do this like that?
Upvotes: 8
Views: 7177
Reputation: 1443
As noted in this link
"This noncompliant code example attempts to read a variadic argument of type unsigned char with va_arg(). However, when a value of type unsigned char is passed to a variadic function, the value undergoes default argument promotions, resulting in a value of type int being passed."
Solution:
Access variadic function with type int and cast it back to unsigned char (or char)
unsigned char c = (unsigned char) va_arg(ap, int);
Upvotes: 3
Reputation: 9343
The compiler just told you why:
'char' is promoted to 'int' when passed through '...'
According to the C language specification, usual arithmetic conversions are applied to the unnamed arguments of variadic functions. Hence, any integer type shorter than int
(e. g. bool
, char
and short
) are implicitly converted int
; float
is promoted to double
, etc.
Do what the compiler asks you for (use va_arg()
with int
as its second parameter), else your code will invoke undefined behavior.
Upvotes: 18