Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to avoid if-else statement inside for-loop but the code seems to have some errors

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

like image 475
user12556559 Avatar asked Dec 18 '19 06:12

user12556559


2 Answers

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);

like image 174
CinCout Avatar answered Nov 03 '22 00:11

CinCout


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);
like image 41
R Sahu Avatar answered Nov 02 '22 23:11

R Sahu