Crazy Chenz
Crazy Chenz

Reputation: 13188

Within scope, will all declarations happen at the beginning of a function after compilation (in C)?

Within scope, will all declarations happen at the beginning of a function after compilation (in C)? The following examples shows a bit better what I am wondering. If something goes wrong with "ptr1", can I assume that ptr2 has been initialized to NULL?

int main()
{
  int ret = 0;

  void * ptr1 = NULL;
  if (ret = do_ptr_work(ptr1))
    goto done;

  void * ptr2 = NULL;
  if (ret = do_ptr_work(ptr2))
    goto done;

done:
  if (ptr1) {
    free(ptr1);
    ptr1 = NULL;
  }
  if (ptr2) {
    free(ptr2);
    ptr2 = NULL;
  }

  return ret;
}

Thanks, Chenz

Upvotes: 2

Views: 106

Answers (2)

caf
caf

Reputation: 239051

No. The initialisation is defined to happen when the declaration is reached. If you jump over the initialisation, the variable exists but is uninitialised.

One relevant part of the C standard is §6.2.4:

If an initialization is specified for the object, it is performed each time the declaration is reached in the execution of the block; otherwise, the value becomes indeterminate each time the declaration is reached.

(Note that this text applies only to objects with automatic storage duration). Another is §6.8:

The initializers of objects that have automatic storage duration, and the variable length array declarators of ordinary identifiers with block scope, are evaluated and the values are stored in the objects (including storing an indeterminate value in objects without an initializer) each time the declaration is reached in the order of execution, as if it were a statement, and within each declaration in the order that declarators appear.

Upvotes: 3

GrahamS
GrahamS

Reputation: 10350

Personally I'd avoid that approach altogether as it seems to get far too close to undefined behaviour for my liking and it is bound to cause problems, either when you move to a different compiler/platform or just when you confuse the maintenance programmers.

Why not just declare the variables at the start of the scope? Looks neater to my eyes anyway.

int main()
{
  void * ptr1 = NULL;
  void * ptr2 = NULL;
  int ret = 0;

  if (ret = do_ptr_work(ptr1))
    goto done;

  if (ret = do_ptr_work(ptr2))
    goto done;

done:
  if (ptr1) {
    free(ptr1);
    ptr1 = NULL;
  }
  if (ptr2) {
    free(ptr2);
    ptr2 = NULL;
  }

  return ret;
}

Or even just refactor completely to remove the goto?

int main()
{
  void * ptr1 = NULL;
  void * ptr2 = NULL;

  int ret = do_ptr_work(ptr1);

  if (!ret) 
    ret = do_ptr_work(ptr2);

  // Tidy up...
  if (ptr1) {
    free(ptr1);
    ptr1 = NULL;
  }
  if (ptr2) {
    free(ptr2);
    ptr2 = NULL;
  }

  return ret;
}

Upvotes: 0

Related Questions