Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange C++ syntax?

Tags:

c++

syntax

This may be a stupid question but I have a code with the following line:

Solver *S, *STP = S = 
UseDummySolver ? createDummySolver() : new STPSolver(true);

I know the ternary operator but it's the equals signs that confuse me a bit. Can anyone give me some explanation ? Thanks.

like image 597
Cemre Mengü Avatar asked Jul 02 '12 20:07

Cemre Mengü


3 Answers

Written out, it's

Solver *S;
Solver *STP;
S = UseDummySolver ? createDummySolver() : new STPSolver(true);
STP = S;

It's very ugly though, I'd not recommend doing that in your code.

The recommended way would be to write it as follows (use initialization, rather than assignment):

Solver *S = UseDummySolver ? createDummySolver() : new STPSolver(true);
Solver *STP = S;
like image 89
houbysoft Avatar answered Nov 11 '22 21:11

houbysoft


I would recommend this:

Solver *S = UseDummySolver ? createDummySolver() : new STPSolver(true);
Solver *STP = S;

It is concise, yet neat and clean.

Also, it uses initialization, rather than assignment. You should prefer initialization over assignment wherever possible.

like image 30
Nawaz Avatar answered Nov 11 '22 22:11

Nawaz


You're looking at chained assignment.

It is the same as:

Solver *S;
Solver *STP;
S = UseDummySolver ? createDummySolver() : new STPSolver(true);
STP = S;
like image 44
NominSim Avatar answered Nov 11 '22 23:11

NominSim