简体   繁体   中英

Why does the following code not produce a compilation error?

I am using VS2005 compiler and I am expecting following code to give compilation error.

int a=1, b= 2, c=3;
a = (b,c);

value of a after assignment is 3. As per my understanding it should give compilation error.

I would be happy to know if there is any valid reason behind this.

The only error in your code is that you forgot the semicolon at the end of the second line, but I assume that was a typographical error in composing your question, rather than the actual thrust of your question.

I see no reason why the code you've shown should produce a compilation error. It compiles just fine for me, and the value of a is, in fact, 3.

See for yourself : the following code returns 3:

int main()
{
    int a=1, b= 2, c=3;
    a = (b,c);

    return a;
}

The trick is your use of the comma operator , which evaluates its first operand and then discards the result, and then evaluates the second operand and returns its value.

However, as Charles Bailey notes, you have to wrap the code shown in the question inside of a function, otherwise you will get compilation errors in any compiler. C++ doesn't allow assignment statements outside of functions.

You are using the comma operator in C++, it is not commonly used. This works as follows

<expression1>, <expression2>

It evaluates <expression1> and discards the results and then evaluates <expression2> and takes the result of that is returned as the value of the whole expression.

There is no error in this piece of code. Why do you think there should be a compilation error? All here is is a comma operator which evaluates all its parameters, but returns the rightmost one: in this case 3.

To quote http://en.wikipedia.org/wiki/Comma_operator :

"In the C and C++ programming languages, the comma operator (represented by the token ,) is a binary operator that evaluates its first operand and discards the result, and then evaluates the second operand and returns this value (and type). The comma operator has the lowest precedence of any C operator, and acts as a sequence point."

I've just tested this on VS2005 and I get compilation errors as expected.

Compiling...
main.cpp
d:\dev\work\comptest\main.cpp(2) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
d:\dev\work\comptest\main.cpp(2) : error C2374: 'a' : redefinition; multiple initialization
        d:\dev\work\comptest\main.cpp(1) : see declaration of 'a'

The declaration line is fine, but as expected the assignment statement is not valid outside of a function. The compiler appears to interpret it as an attempt to re-initialize a with a default int type, neither of which is legal.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM