Search code examples
cgccclang

GCC will compile but clang wont


So in my finals there was an exercise asking what will the program print.

This is the code:

#include <stdio.h>

int main (){
    int x=5, y=4;

    if (x>y);
      printf("A");

    if(x=4)
      printf("%d",x+y);

     return 0;
}

When I try to compile it using gcc -ansi -pedantic -Werror on a Debian machine, it compiles just fine and outputs "A8".

However, when I try to compile it using clang -ansi -pedantic -Werror, I receive errors regarding the if (x=4) expression missing = and missing statement on if(x>y);.

Why does that happen, and which answer could be marked as correct?


Solution

  • compilers may emit different warnings. For example clang warns about empty statement and gcc does not.

    So if you set -Werror it will compile using gcc but will not compile using the clang.

    BTW what is stopping you from reading the compiler messages. They are self-explanatory. It even shows how to correct it.

    #1 with x86-64 clang 9.0.0
    
    <source>:6:9: error: if statement has empty body [-Werror,-Wempty-body]
    
    if (x>y);
    
            ^
    
    <source>:6:9: note: put the semicolon on a separate line to silence this warning
    
    <source>:8:5: error: using the result of an assignment as a condition without parentheses [-Werror,-Wparentheses]
    
    if(x=4)
    
       ~^~
    
    <source>:8:5: note: place parentheses around the assignment to silence this warning
    
    if(x=4)
    
        ^
    
       (  )
    
    <source>:8:5: note: use '==' to turn this assignment into an equality comparison
    
    if(x=4)
    
        ^
    
        ==
    
    <source>:12:2: error: no newline at end of file [-Werror,-Wnewline-eof]
    
    }
    
     ^
    
    3 errors generated.
    
    Compiler returned: 1