1

I was editing the source code of a program I had written few days back, and observed an interesting thing.

I had below two statements:

newNode->data = 5

and

newNode->next = NUll

And there was a comma (,) instead of a semi-colon (;) separating above two statements. I was surprised because, I always thought this should result in an error.

Below, I have written a short C program to show what I mean to ask.

#include<stdio.h>
#include<stdlib.h>

/*node structure definition*/
struct node
{
    int data;
    struct node *next;
};

/*----------main()------------*/
int main(int argc, char *argv[])
{
    struct node *newNode = NULL;    
    newNode = malloc(sizeof(struct node));

    /*Below is the interesting statement*/

    /*LABEL: QUESTION HERE*/

    newNode->data = 5,
    newNode->next = NULL;

    printf("data: %d\n",newNode->data);

    while(newNode->next != NULL)
    {
        printf("Not Null\n");
    }

    return 0;
} 

Please see below compilation and sample run of the above program.

Lunix $ gcc -Wall testComma.c -o testComma
Lunix $ ./testComma
data: 5
Lunix $

As you see, the program compiles and run with no issues.

Using comma (,) instead of semi-colon (;) should not result in an error here ? Why ?

I thought I knew what C statements are but looks like I don't! Could someone explain the reason why there is no error in this case?

Cœur
  • 37,241
  • 25
  • 195
  • 267
sps
  • 2,720
  • 2
  • 19
  • 38
  • 1
    The comma operator : http://en.wikipedia.org/wiki/Comma_operator – Prabhu Apr 16 '15 at 05:14
  • 1
    Most common place to see the comma operator in C is in a `for` loop with multiple initialisations. Many languages support the comma operator in a similar way, including C++, Java , C# and Perl. – cdarke Apr 16 '15 at 06:48

1 Answers1

4

You can't separate two C statements with a comma. You can, however, separate two C expressions with a comma, because , is an operator (which evaluates its two operands in order, first left and then right, and finally returns the right-hand one).

In addition, a = b is an expression. However, one of the possible C statement types is an expression, so you can use any expression as a statement, including a + b;, a = b;, and a = b, a + b;

rici
  • 234,347
  • 28
  • 237
  • 341
  • thanks. now i see there are a different types of c statements, one of them is expression. I felt like i was asking what is a,b,c,d,e after learning how to make sentence. Any case, good to have it cleared. Thanks for the help. – sps Apr 16 '15 at 05:27