-3

I am looking at some open source software and they use a for loop/operators in a different way then I have seen and I was wondering if someone can tell me what it is doing in English. I believe the open source is in C, maybe C++, not sure if it makes a difference but I am working in C++.

The for loop given is, TSTEP=60, tt and t are just double variables

for (tt=t<0.0?-TSTEP:TSTEP;fabs(t)>1E-9;t-=tt)
Konrad Rudolph
  • 506,650
  • 124
  • 909
  • 1,183
user2840470
  • 879
  • 8
  • 20

3 Answers3

5
    if(t < 0)
        tt = -TSTEP;
    else
        tt = TSTEP;

    for(; fabs(t) > 1E-9; t -= tt)

Hopefully this is deciphered enough

SirGuy
  • 10,480
  • 2
  • 36
  • 66
2

It's certainly ugly code, but really the only confusing part is the first part of the for statement:

tt=t<0.0?-TSTEP:TSTEP;

It might be easier to read with brackets:

tt = (t < 0.0 ? -TSTEP : TSTEP);

In English, this is "if t is less than 0.0, assign -TSTEP to tt, otherwise assign TSTEP to tt". If you haven't seen this syntax before, look up the ternary operator.

Community
  • 1
  • 1
Joseph Mansfield
  • 104,685
  • 19
  • 232
  • 315
1

I guess the ?: operator is what puzzles you. The loop itself changes t by tt (60) steps in the direction towards 0, until t is almost 0, independent of if t was positive or negative from the start. lvalue = (expr ? a : b) is a common shorthand for

if (expr) {
  lvalue = a;
} else {
  lvalue = b;
}