1

Hi I am puzzled and don’t know what this test condition mean in this loop.

j<+i

Can someone please explain how it works and how to read it step by step?

for(int i = 0; i<5; i++)

  for(int j = 0; j<+i; j++)
selbie
  • 100,020
  • 15
  • 103
  • 173
Learner
  • 51
  • 2
  • 5
  • `+i` should be equivalent to `i` which means the condition should be equivalent to `j < i`. I don't see the point of it. – patatahooligan Oct 08 '19 at 06:35
  • 1
    Highly likely that it's just a typo. `j < +i` gets evaluated the same as `j < (+i)` which is the same as `j < i` – selbie Oct 08 '19 at 06:35
  • Possible duplicate of [What does the unary plus operator do?](https://stackoverflow.com/questions/727516/what-does-the-unary-plus-operator-do) – Blaze Oct 08 '19 at 06:35
  • 2
    It's almost certainly a typo. Someone accidentally held SHIFT after typing `<` and turned `=` into a `+`. – Blastfurnace Oct 08 '19 at 06:45

2 Answers2

4

The unary plus operator + is a no-op with the exception that the expression +a is at least as wide as an int.

So in your case it is a no-op, but it can make a difference on the odd occasion:

#include <iostream>

void foo(int a){
    std::cout << "pay me a bonus\n";
}

void foo(char a){
    std::cout << "format my hard disk\n";
}

int main()
{
    char a = '0';
    foo(a);
    foo(+a);
}
Bathsheba
  • 231,907
  • 34
  • 361
  • 483
1

The '+' isn't needed within this context (it's a unary + operator, but no one ever uses it because it's mostly pointless). i == +i.

for(int i = 0; i < 5; i++)
{
  for(int j = 0; j < i; j++)
  {
  }
}
robthebloke
  • 9,331
  • 9
  • 12
  • '+' can be used to print the value in a 8-bit value. It outputs the value instead of an ascii character. This is true at least with cout without any iomanip. https://stackoverflow.com/a/31991844/12160191 for reference. – Empty Space Oct 08 '19 at 06:44
  • 1
    @TrickorTreat -- that behavior isn't really about printing. For `char ch`, the type of `+ch` is `int`. Yes, the stream inserter for a `char` treats the value as a character code and the stream inserter for an `int` treats the value as a value. But that also applies in any other situation that involves overloaded functions, as the answer by Bathsheba points out. – Pete Becker Oct 08 '19 at 10:34
  • @PeteBecker Got it, Thanks :) – Empty Space Oct 08 '19 at 11:57
  • Just to clarify. In the code above Variable i is 0. Variable j is 0. Then in the 2nd for loop parameter the test condition is j<+i, doesn’t it mean this: 0<+1+0 aka j – Learner Oct 09 '19 at 02:25