networking · beginner · ~15 min

Allocate a connection id

Hand out monotonically increasing ids.

Challenge

Hand out a unique, monotonically increasing id to each accepted connection by reading and bumping a shared counter.

Task

Implement int next_conn_id(int *counter) that returns the current value of *counter and then increments *counter (a post-increment), so successive calls yield 0, 1, 2, ...

Input

A pointer counter to the next id to hand out.

Output

Returns the value of *counter before the increment; *counter is left one higher.

Example

counter starts at 0:
next_conn_id(&counter)   ->   0   (counter now 1)
next_conn_id(&counter)   ->   1   (counter now 2)
next_conn_id(&counter)   ->   2   (counter now 3)

Edge cases

  • The returned value is the old value; the side effect on *counter is what makes ids unique.

Input format

A pointer to the int counter holding the next id.

Output format

The pre-increment value of *counter; *counter is incremented.

Constraints

Return the old value, then increment (post-increment semantics).

Starter code

int next_conn_id(int *counter) {
    /* TODO */
    return 0;
}

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.