Skip to main content

Command Palette

Search for a command to run...

Comma as an operator in C

Published
•1 min read•View as Markdown

To separate two or more expressions we use the comma operator in C. Where expression1 is evaluated first, and after that expression2, and the value of expression2 is returned for the entire expression.

#include <stdio.h>

int main() {
    int y;
    y = 10,20,30,40;
    printf("\n  y is %d ",y);

    int x;
    int z = (x=2,x+4);
    printf("\n  z is %d ", z);

    return 0;
}

When initialization of a variable while declaring it, you have to use parentheses:

#include <stdio.h>

int main() {
//when initializing, it behaves as follows
    int p=(10,20,30); //correct 
    int q = 10,20,30; //incorrect
    printf("%d %d",p,q);

    return 0;
}

Correct way:

#include <stdio.h>

int main() {
//when initializing, it behaves as follows
    int p=(10,20,30); //correct 
    //int q = 10,20,30; //incorrect
    printf("\n     %d",p);

    return 0;
}

Please refer to https://www.geeksforgeeks.org/comma-in-c/ for more interesting examples.

Also beware that in some cases, using comma operator in this way may lead to ambiguous code and undefined behavior.

9 views

More from this blog

P

Programming Tutorials

89 posts