Comma in C

— 417 words — 3 min

#programming 


Do you know what this C code produces?

#include <stdio.h>
int main() {
    if (1,0) {
        puts("hello");
    }
}

This code does not print “hello”. When the comma is used in such a case it acts as binary operator. This means the condition in the if statement is evaluated as follows:

You could use more than two expressions separated by a comma. In general, the expressions are elevated from left to right and the rightmost result is returned. If you do this and you turn on -Wunused-value (or -Wall for that matter), your compiler will tell you about this.

$ gcc -Wall main.c && ./a.out
main.c: In function ‘main’:
main.c:3:14: warning: left-hand operand of comma expression has no effect [-Wunused-value]
    3 |         if (1,0)
      |              ^

You can use this in variable initialization as well.

// number would be 42. The number 22 is just discarded.
int number = (22,42);

Or call functions:

#include <stdio.h>

// return 1 on success
int call_grandma() {
    puts("log: call_grandma()");
    // do things
    return 1;
}

int answer_to_everything() {
    return 42;
}

int main() {
    int answer = (call_grandma(), answer_to_everything());
    printf("answer=%d\n", answer);
    // answer is now 42.
    // grandma was also called but the result was discarded.
}

Executing the above program results in this output.

$ gcc main.c && ./a.out
log: call_grandma()
answer=42

Other more common uses that you probably know are the comma as a separator, for example

Sometimes, the comma can also be used in place of a semicolon.

#include <stdio.h>
int main() {
    puts("good"),
    puts("morning"),
    puts("world");
}

Yes, this works.

You can find more examples and some more detailed explanations on GeeksForGeeks.


Articles from blogs I follow around the net

Status update, October 2024

Hi! This month XDC 2024 took place in Montreal. I wasn’t there in-person, but thanks to the organizers I could still ask questions and attend workshops remotely (thanks!). As usual, XDC has been a great reminder of many things I wanted to do but which got bur…

via emersion October 21, 2024

Wealth = Have ÷ Need

Not a new idea, but just another visualization and reminder. Wealth, feeling like you have plenty, is an equation. Wealth = Have ÷ Need If you have nothing, then focus on having some. Once you have some, the easiest way to increase your wealth is to decrease …

via Derek Sivers blog September 27, 2024

Installing NetBSD on Linode

Instructions on how to install NetBSD on a Linode instance. All steps are performed via the command-line and serial console.

via Signs of Triviality September 14, 2024

Generated by openring