Hacker News new | ask | show | jobs
by ablob 464 days ago
You could write this in C, no?

  { int val; if (getFoo(&val)) {
    ...
  }}
Both ways of expressing this are weird, but stating that this can't be achieved with C is dishonest in my opinion.
2 comments

If I reformat this,

    {
        int val; 
        if (getFoo(&val)) {
    
        }
        printf("%d", val);
    }
The bug is still possible, as you've introduced an extra scope that doesn't exist in the C++ version.

Also, this was one example. There are plenty of other examples.

it's not that weird to explicitly limit the scope of certain variables that logically belong together.

But i agree the C++ if(init;cond) thing was new to me.

Like everything in C++, it has it's share of footguns

    if (Foo* f = GetPtr(); f->HasValue()) {} // wrong; f can be null
vs

    if (Foo* f = GetPtr(); f && f->HasValue()){}
Is probably the biggest pitfall. Especially if you're used to this:

    if (Foo* f = GetPtr())
    {
        f->DoTheThing(); // this is perfectly safe.
    }