Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'Char' is promoted to 'int' when passed through in C

Tags:

c

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?

like image 787
Chris Avatar asked Dec 06 '22 01:12

Chris


1 Answers

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.

like image 144
The Paramagnetic Croissant Avatar answered Dec 14 '22 22:12

The Paramagnetic Croissant