Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why am I not getting a compilation error?

I have following code:

#include <iostream>

char add(char a, int b)
{
    return a + b;
}

int main(void)
{
    long long a = 100000000;
    long long b = 20;

    int x = add(a, b);

    std::cout << x << std::endl;

    return 0;
}

And I dont understand why does my code compile without any warnings.

Shouldn’t the GCC compiler with the -Wall flag give me a type mismatch error?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This is not an error it is a valid implicit conversion, although it involves narrowing the type. You can get warning about this with e.g. -Weverything in clang which will emit

<source>:13:17: warning: implicit conversion loses integer precision: 'long long' to 'char' [-Wimplicit-int-conversion]
   13 |     int x = add(a, b);
      |             ~~~ ^
<source>:13:20: warning: implicit conversion loses integer precision: 'long long' to 'int' [-Wshorten-64-to-32]
   13 |     int x = add(a, b);
      |             ~~~    ^    
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading