no error: using comma or semicolon

Hi, I use Dev C++. I want to learn that, When I put a comma end of a statement. Compiler runs and there is no error. But books write you should use semicolon. Why doesn't the compiler give error?
See the "Comma Operator ( , )" section on this page:
http://www.cplusplus.com/doc/tutorial/operators/

(also known as the "sequence operator" or even "binary sequence operator")

The comma does not end the statement. It is part of a longer statement which ends with a semi-colon.

When used with functions, the comma does the same things as calling the functions in separate statements.

start(), stop();

does the same as

start(); stop();

or

1
2
start();
stop();


But note that you can not get at the return code of the first function unless you use an extra variable.

int ret = start(), stop();

will end up with the return code from stop, having thrown away the one from start().

And the example given as part of the comma operator explanation

1
2
3
4
int a = 0;
int b = 0;

a = (b=3, b+2);


is the same as

1
2
3
4
5
int a = 0;
int b = 0;

b=3;
a = b+2;


The example is a bit daft. Real code like that would be very annoying! But the comma operator is useful when initializing loop control variables.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
using namespace std;

void process(char ch)
{
	cout << ch;
}

int main()
{
	const char val[] = "hello world";

	for(size_t idx = 0, len = strlen(val); len > idx; ++idx)
	{
		process(val[idx]);
	}

	process('\n');

	return 0;
}


This is better than

1
2
3
for(size_t idx = 0, strlen(val) > idx; ++idx)
{
    ...


(esp. for long strings) as you only calculate the length of the string once (the strlen function starts at the beginning and steps forward until it find the null term.)

And is better than

1
2
3
4
5
size_t len = strlen(val) ;

for(size_t idx = 0, len > idx; ++idx)
{
    ...


as len can only be seen inside the for loop's body (i.e. is tightly scoped)

Andy

PS also see http://en.wikipedia.org/wiki/Comma_operator

Last edited on
Semi colons are used to end each statement. If a comma is used, a semi-colon is expected later.

Here is an example:
if (bCondition) a = 1, b = 1;.

Is pretty much the same as:
1
2
3
4
if (bCondition)  {
    a = 1;
    b = 1;
}


meawhile the following:
if (bCondition) a = 1; b = 1;

Is pretty much the same as:
1
2
3
4
if (bCondition) {
    a = 1;
}
b = 1;


The difference is the comma.

Now, if you don't use a semi-colon at all, you'll get a compilation error once you reach a } as in the following:
1
2
3
if (bCondition) {
    a = 1,
}
Last edited on
Gah, I was ninja'd! But andywestken's answer is better than mine. I learned!
Last edited on
thanks for your answers :)
Topic archived. No new replies allowed.