0

I am trying to understand the comma Operator in C and I have encountered this compilation error. Can somebody help me?

#include <stdio.h>

int main(void)
{
    int a = (1,2);
    printf("%d", a);
}

I am using a GCC compiler. I expect the variable "a" value to equal 2 and print it out as output by the printf. But the following warning is generated.

Output:

test.c:5:11: warning: expression result unused [-Wunused-value]
        int a = (1,2);
                 ^
1 warning generated. 

  
Ku-hello
  • 35
  • 5
  • Why do you think that's an error? – Joseph Sible-Reinstate Monica Dec 21 '21 at 03:53
  • Does this answer your question? [What does the comma operator , do?](https://stackoverflow.com/questions/52550/what-does-the-comma-operator-do) – kaylum Dec 21 '21 at 03:54
  • "*I expect a value to equal 2 and print it out in the next line*". You'll never get that from the compiler output. You need to run the binary that the compiler produces. Did you do that? Please show your exact commands. – kaylum Dec 21 '21 at 03:56
  • @ Joseph Sible-Reinstate Monica. I expect it to store a = 2. – Ku-hello Dec 21 '21 at 03:57
  • @kaylum I did, "gcc test.c". Do i need to do something else? – Ku-hello Dec 21 '21 at 03:59
  • Yes. That will produce a default `a.out` binary. Run with `./a.out`. Please consider reading a good C book or tutorial as this should be covered in any such reference material. – kaylum Dec 21 '21 at 04:02
  • @kaylum https://www.geeksforgeeks.org/comna-in-c-and-c/. I expect this to happen. Assign value of 2 to variable a. – Ku-hello Dec 21 '21 at 04:10
  • What about the previous comment?? Did you manage to [run it](https://ideone.com/O5lTrH)? Your code does do that. You just need to run it properly to see it. The compiler is just telling you that you are throwing away the `1`. – kaylum Dec 21 '21 at 04:12

1 Answers1

1

Your compiler is configured to treat warnings as being fatal. Normally it is not a good idea to disable that but for this experimental case you can disable it with -Wno-error.

$ gcc -Wno-error test.c
test.c:9:14: warning: expression result unused [-Wunused-value]
    int a = (1,2);
             ^
1 warning generated.
$ ./a.out
2
kaylum
  • 13,833
  • 2
  • 22
  • 31
  • It was producing `a.out` file. I just didn't see it, presuming that warning to be a compilation error. It worked. Thanks. – Ku-hello Dec 21 '21 at 04:35