Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com
Answertopia.com

How To Guides
Virtualization
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
Problem Solutions
Privacy Policy

  




 

 

The GNU C Programming Tutorial - The comma operator

Node:The comma operator, Next:, Previous:Hidden operators and values, Up:Advanced operators



The comma operator

The comma operator (,) works almost like the semicolon ; that separates one C statement from another. You can separate almost any kind of C statment from another with a comma operator. The comma-separated expressions are evaluated from left to right and the value of the whole comma-separated sequence is the value of the rightmost expression in the sequence. Consider the following code example.

#include <stdio.h>

/* To shorten example, not using argp */
int main (int argc, char *argv[], char *envp[])
{
  int a, b, c, d;

  a = (b = 2, c = 3, d = 4);
  printf ("a=%d\nb=%d\nc=%d\nd=%d\n",
	  a, b, c, d);
  return 0;
}

The value of (b = 2, c = 3, d = 4) is 4 because the value of its rightmost sub-expression, d = 4, is 4. The value of a is thus also 4. When run, this example prints out the following text:

a=4
b=2
c=3
d=4

The comma operator is very useful in for loops. (See The flexibility of for, for an example.)

 
 
  Published under free license. Design by Interspire