Home > Net >  c give no warning or error when a integer is passed to a function that has char arguments
c give no warning or error when a integer is passed to a function that has char arguments

Time:10-10

Why does c give no warning or error when a integer is passed to a function that takes char arguments.

void test(char a) {
    std::cout << a;
}


test(1);

I would get unexpected behaviour doing so(ie a ? is getting printed). But I was expecting this to be an error or atleast a compilation warning as some sort of cast was happening. Why is this not happening?

CodePudding user response:

I'm not really sure why c allow implicit conversion here, maybe because it's good for dealing with raw memory.


For why you get unexpected behavior

1 is a valid control code like '\0' or '\n'

while you should use '1' (or 49, assume ASCII or compatible format)


Compiler would warn if it does not fit in.

void test(char c);
void F(){test(1);} // OK
void G(){test(10000);} // warning 
void H(int v){test(v);} // need -Wconversion

Compiler Explorer

  • Related