I was playing around with the ,
operator after reading several of the answers on a Stack Overflow post (What does the comma operator , do?). Further, I was playing around with the ,
separator after reading this post: comma operator and comma seperator in c++. Consider the following two code snippets:
Code 1
#include<stdio.h>
int main(void)
{
int a, b; /* comma functions as a separator */
a = 5, b=9; /* NOT SURE how comma functions */
printf("a = %d \n",a) , printf("b = %d \n",b); /* comma functions as an operator */
}
Code 2
#include<stdio.h>
int main(void)
{
int a, int b; /* not allowed - compiler error ... NOT SURE how comma functions */
a = 5, b=9; /*NOT SURE how comma functions */
printf("a = %d \n",a) , printf("b = %d \n",b); /*comma functions as an operator */
}
The top code (Code 1) is fine...and prints out a=5
and b=9
; however, the bottom code (Code 2) does not make it past the compiler and cites the int a, int b ;
line as the incriminating action.
There are a lot of questions bundled up in these two code snippets but I'll bullet out the ones I care about the most:
In the statement
a=5,b=9;
is that,
functioning as a separator or an operator? I've read that in initialization statements, commas function as separators. However, given my understanding of what a comma operator would do, I feel like classifying this comma as an operator makes sense as well.Why is
int a, int b
not allowed? If the comma was allowed to behave as an operator, then certainly this would make sense, right?int a
would be evaluated first and it would have the side effect of labeling some place in memory with the identifier ofa
and thenint b
would be processed in a similar way. Therefore, it seems as though the compiler does not want to alter the interpretation of the,
in this case (i.e. it only ever wants to think of it as a separator).
An explanation would be greatly appreciated! Thanks~