This snippet works just fine.
for (int i = 0; i < 1; i++) // for some other purpose
{
// some other code
double** angle = new double* [10]; // for a 2D matrix
for (int j = 0; j < 10; j++)
{
angle[j] = new double [3];
if (j == 0)
angle[j][0] = 2; // focused on the first column for now
else
angle[j][0] = angle[j-1][0]+3;
std::cout << angle[j][0] << std::endl;
}
for (int i = 0; i < 10; i++)
delete[] angle[i];
delete[] angle;
}
I am trying to not use conditional statement inside the loop. If I replace that with the following line, the code stops working. Please help me understand it.
angle[j][0] = (j == 0) * 2 + (j != 0) * (angle[j-1][0] + 3);
Using g++ -std=c++11 -o out main.cpp; ./out
on Ubuntu 16.04 LTS
You're trying to use the ternary operator, but the syntax is wrong.
Do this:
angle[j][0] = (j == 0) ? 2 : (angle[j-1][0] + 3);
The line
angle[j][0] = (j == 0) * 2 + (j != 0) * (angle[j-1][0] + 3);
does not work since you access angle[-1]
when j
is 0
. That is a reason for undefined behavior.
Looking at your comment to the other answer, you are apparently looking for using the conditional operator.
angle[j][0] = (j == 0) ? 2 : (angle[j-1][0] + 3);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With