0

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?

7
  • = is not the same operator as ==. Commented Jan 10, 2020 at 16:47
  • Yes I do get that.What I do not understand is why it compiles in GCC and it does not in clang. Commented Jan 10, 2020 at 16:49
  • 1
    So apparently gcc is believing that you know what you are doing, while clang is not :) Commented Jan 10, 2020 at 16:49
  • if (x>y); printf("A"); is equal to if (x>y) { /* empty block */ } printf("A"); Commented Jan 10, 2020 at 16:49
  • Does gcc -Wall -Wextra -Wpedantic make any difference? Commented Jan 10, 2020 at 16:51

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.