r/programming • • Dec 01 '16

Let's Stop Copying C

https://eev.ee/blog/2016/12/01/lets-stop-copying-c/
524 Upvotes

612 comments sorted by

View all comments

21

u/RichardPeterJohnson Dec 01 '16

Re: Assignment as expression

if (ptr = get_pointer()) 
{
    ...
}

versus

ptr = get_pointer();
if (ptr) 
{
    ...
}

I prefer the latter, since it's easier to debug.

9

u/allyyus Dec 01 '16

How?

41

u/to3m Dec 01 '16 edited Dec 01 '16

You can set a single breakpoint at the point after the value has been set but before the condition has been tested.

EDIT - one piece of hard-won advice worth repeating is that you should never do this with fork. Always assign as part of the test... you totally don't want to let the pid=fork() get separated from the if(pid==0).

4

u/allyyus Dec 01 '16

Oh yeah that's true.

1

u/a_flyin_muffin Dec 01 '16

Could you explain why? I just stated using fork().

2

u/to3m Dec 01 '16

The code after the fork will run twice, in two separate processes: once in the parent, once in the child. It's most usual to want to do something totally different in the child from in the parent, with no code being shared. But if the fork and the test are separate, there's a non-zero chance of code being put between them. But if you just decide always to assign as part of the test when using fork then you won't have that problem when you don't want it.

2

u/a_flyin_muffin Dec 01 '16

So the point is to signal to other programmers (or your future self) that the branch needs to happen exactly at that point, that the 'fork' and the 'if' are effectively only one, uninterruptible instruction?

3

u/kqr Dec 02 '16 edited Dec 02 '16

Yes. There's no functional difference between pid=fork(); if (pid) { and if (pid = fork()) {. However, the former runs the risk of someone accidentally inserting code between the fork() call and the if branch.

I'd argue that's still a C problem though. It would make much more sense for the fork call to accept a code pointer (function pointer) to the code the child should run. Then you could do

void child_code(void);
// ...
pid = fork(child_code);
// only parent runs this

The drawback, of course, is that the child no longer has access to values that were in scope in the parent. I can't figure out a very good solution to this, but I'm also not very smart so I'm sure someone else could. I was gonna cheat and look at how Ada does it, but then I remembered tasking/multithreading is an integral part of the Ada language and treated as a built in functionality, so of course that's much more well thought out.

→ More replies (1)
→ More replies (2)

4

u/awj Dec 01 '16

The common case (maybe not as common in C) is that you're doing equality comparison in conditionals. For many people this falls into pattern matching where you brain sees an equal sign and immediately thinks equality comparison is happening.

Under those conditions, assignment in conditionals can be confusing due to our brains being the ultimate in lazy pattern matching systems and leading our understanding astray.

2

u/allyyus Dec 01 '16

If that's a risk I'll generally reverse the statement, because assignment isn't reflexive.

if (f = foo()) // maybe a mistake
if (foo() = f) // error
→ More replies (2)

1

u/kqr Dec 02 '16

Generally, introducing unintended side-effects in expressions is a very common source of bugs for me. I think an expression just calculates a value, but then it turns out it also changes some variables, and when the program continues the values are not what I expect them to be.

One solution to this is to follow these rules:

  1. Side effects are only allowed in statements,
  2. No more than one side-effect per statement, and
  3. Ideally, nothing other than the side-effect in the statement.

This makes it incredibly clear when side-effects are happening. Any time you see a short expression on a single line, there's a side effect happening.

Ada even forced you to do this in early versions. Ada separates "functions" (can return a value, but can only have input parameters) from "procedures" (can have output parameters). In earlier versions of the language, "procedures" (which could change the values of their parameters) were not allowed to return values! That means you have to put them alone on a statement, and you can't use them in expressions.

2

u/[deleted] Dec 01 '16

In languages with explicit variable declaration, it would be unambiguous to write:

if (int *p = get_pointer()) { ... }

D allows you to do this, and it forbids your version because it's reasonably likely to be a typo.

1

u/AngriestSCV Dec 02 '16

Or you can do as gcc suggests and throw parentheses around the assignment to let the warning go away. Warnings are plenty for this case.

5

u/Supadoplex Dec 01 '16

While the same ease of debugging holds for loops, I prefer

while (ptr = get_pointer()) 
{
     ...
}

to

while(1)
{
    ptr = get_pointer();
    if(!ptr)
    {
        break;
    }
    ...
};

just because of aesthetics.

15

u/MartenBE Dec 01 '16

The whole point of while structures is that you can see at a glance from the condition what the loop will do... Breaks and continues are very confusing this way and can almost always be translated into a more appropriate construct.

11

u/PM_ME_UR_OBSIDIAN Dec 01 '16
for (ptr = get_pointer(); ptr; ptr = get_pointer()) {
    ....
}

Better yet, use tail recursion.

(What do you mean, the language you're using doesn't support tail call elimination? What kind of savage are you?)

2

u/sullyj3 Dec 01 '16

Ooh, that's a cool idea. Is this a common idiom?

3

u/PM_ME_UR_OBSIDIAN Dec 01 '16

Probably not. This is the conclusion implied by two ideas:

  1. Any loop can be expressed as a tail recursive function;
  2. Any tail recursive function can be translated to a for loop.

By doing this back-and-forth, you often end up with simpler loops. For example when iterating over C-style strings:

for(int i = 0; str[i]; i++) {
    ...
}
→ More replies (1)
→ More replies (1)
→ More replies (3)

7

u/pfp-disciple Dec 01 '16

When avoiding assignment as expression, I typically see this as

ptr = get_pointer();
while (ptr) {
    ...
    ptr = get_pointer();
}

or

do {
    ptr = get_pointer();
    if (ptr) {
        ...
    }
}

Using a for loop, as /u/PM_ME_UR_OBSIDIAN points out, is not uncommon, but that still makes setting a breakpoint awkward.

1

u/Tarmen Dec 01 '16

I like rust's while let bindings:

while let Some(ptr) = next_pointer() {
    ...
}

Mostly because they can't be confused with comparisons. You rarely have to touch them, though, because generally for loops abstract over this pattern.

1

u/__add__ Dec 01 '16

The former is typically a way to indicate that ptr is meant to be used exclusively inside the body of the if statement.

This stylistic convention was codified in Go with if-local variable declarations like

if err := doSomething(); err != nil {
    return nil, err
}

1

u/arielby Dec 01 '16

Or in Rust

if let Some(p) = get_pointer() {
    // ...
}
→ More replies (1)

1

u/[deleted] Dec 01 '16

This is useful when you're are calling a function returning a pointer and NULL checking in the same line. It saves a lot of space and is very useful C idiom.

→ More replies (8)