A comma operator question

Consider the following C programs.

// PROGRAM 1
#include<stdio.h>
int main(void)
{
    int a = 1, 2, 3;
    printf("%d", a);
    return 0;
}

The above program fails in compilation, but the following program compiles fine and prints 1.

// PROGRAM 2
#include<stdio.h>
int main(void)
{
    int a;
    a = 1, 2, 3;
    printf("%d", a);
    return 0;
}

And the following program prints 3, why?

// PROGRAM 3
#include<stdio.h>
int main(void)
{
    int a;
    a = (1, 2, 3);
    printf("%d", a);
    return 0;
}

In a C/C++ program, comma is used in two contexts: (1) A separator (2) An Operator.

Comma works just as a separator in PROGRAM 1 and we get compilation error in this program.

Comma works as an operator in PROGRAM 2. Precedence of comma operator is least in operator precedence table. So the assignment operator takes precedence over comma and the expression “a = 1, 2, 3” becomes equivalent to “(a = 1), 2, 3”. That is why we get output as 1 in the second program.

In PROGRAM 3, brackets are used so comma operator is executed first and we get the output as 3.

Disclaimer: This does not belong to TechCodeBit, its an article taken from the below
source and credits.
source and credits:https://www.geeksforgeeks.org/a-comma-operator-question/
We have built the accelerating growth-oriented website for budding engineers and aspiring job holders of technology companies such as Google, Facebook, and Amazon
If you would like to study our free courses you can join us at

http://www.techcodebit.com. #techcodebit #google #microsoft #facebook #interview portal #jobplacements
#technicalguide

rakesh

Leave a Reply

Your email address will not be published. Required fields are marked *

Skip to toolbar