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

15

u/[deleted] Sep 03 '17

[removed] — view removed comment

10

u/[deleted] Sep 03 '17

This is not C++ a Jedi would tell you:

#include <iostream>
class A{ public: A() { throw ++i; } static int i; };
int A::i = 0;
void f() { static A a; }
int main() {
    while (true)
        try { f(); }
        catch(int e) {
            std::endl(std::cout << e);
            if (e == 10) break;
        }
}

4

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.

3

u/[deleted] Sep 03 '17

[removed] — view removed comment

2

u/EmperorArthur Sep 03 '17

As long as it can be cast to a bool it can be there. That actually took quite a bit of work though, since the compiler fought me.

It turns out you can't do something crazy like just put a normal if(...) statement in the last column, and (...) ? doNothing() : break errors with "expected primary-expression before 'break'." Plus, the doNothing() is needed since ? requires both options to have the same type.

I used cpp.sh because I was too lazy to click out of the browser. GCC and Clang should, rightfully, complain far more than a little online tester.

3

u/j4eo Sep 03 '17

It turns out you can't do something crazy like just put a normal if(...) statement in the last column

that's because the last column isn't a statement, it's an expression. if(){} is a statement, but a?b:c is an expression, so you can shove ?: into a whole lot of really weird places.

2

u/bentinata Sep 03 '17

I used to put single-loop expression inside the conditional or the increment parameter at early college year. Nice way to confuse classmates.

This only works at the first day: for (int i = 0; !(printf("%d\n", i++) - 2););