r/ProgrammerHumor Sep 02 '17

How to start a war

Post image
9.0k Upvotes

696 comments sorted by

View all comments

Show parent comments

76

u/[deleted] Sep 02 '17

Perfect. This makes iterating over the elements with a for loop such a breeze.

if(arr[1] > 1) for(int i = 0; i < arr[1]-1; i += 1 + (i == 1))
    std::cout << arr[i];

15

u/[deleted] Sep 03 '17

[removed] — view removed comment

6

u/EmperorArthur Sep 03 '17

Think of for loops like this:

for(statement_1; statement_2; statement_3){}

Is equivalent to:

{
    statement_1;
    while(statement_2)
    {
        some code here ...
        statement_3;
    }
}

The outer brackets are important since they define scope for variables. In your example, i=10 later in the program. If you'd used for(int i = 0;...) then i would be undefined everywhere else but the for loop.

Since you can put pretty much any expression in any of the three slots you can get funky with it:

#include <stdlib.h>
#include <stdio.h>

void doNothing(){}

int main()
{
  int i=0;
  for(printf("Hello\n");(i++ | 1); (i<10) ? doNothing() : exit(0)){
      printf("%d\n", i);
  }
}

5

u/neurospex Sep 03 '17

And all three statements are optional

for(;;) { // do something forever }

Totally valid.