Author Topic: Require explicit (un)initialization.  (Read 100 times)

lerno

  • Full Member
  • ***
  • Posts: 239
    • View Profile
Require explicit (un)initialization.
« on: January 30, 2019, 06:07:18 PM »
Instead of warning on non-initialized variables and explicitly initializing, consider the following change:

Code: [Select]
int a; // a initialized to 0, as if it was static.
int a = 10; // a initialized to 10
int a = uninitialized; // a not initialized, warning if used before later assignment.

Alternatives to uninitialized:

Code: [Select]
int a = ---;
int a = *;
int a = ?;

chqrlie

  • Newbie
  • *
  • Posts: 14
    • View Profile
Re: Require explicit (un)initialization.
« Reply #1 on: January 30, 2019, 09:06:15 PM »
I don't like mandatory initialization either, but implicit initialization to the zero value of the type is confusing too. The compiler should just issue an error, not a warning when it detects that a variable is used before intialization. There are border cases where it is difficult, or plain impossible to determine if a variable was initialized or not, requiring explicit initialization in these cases is OK IMHO. This is basically what I get with `-Wall -Werror`.

Regarding a possible syntax to specify uninitialized status, I would suggest:

Code: [Select]
int a = void;  // a not initialized, warning if used before later assignment.
This could be used to tell the compiler that a variable is no longer valid and thus prevent its use in further computations. For example:

Code: [Select]
free(p);
p = void;
return p;   // error: use of an invalid value.


lerno

  • Full Member
  • ***
  • Posts: 239
    • View Profile
Re: Require explicit (un)initialization.
« Reply #2 on: January 31, 2019, 12:43:19 AM »
I like the reuse of void.

In regards to int a; initialized to zero implicitly - I understand the thought that this is counter to whar one usually expects. On the other habd this makes static and local variables behave exactly the same way and it simplifies how one reasons about struct init.

For example, it is more natural to expect Foo f = { .one_field = 1 } to actually zero out all other fields in the struct if we have implicit zeroing.

An alternative would be to disallow int a; completely, requiring it to either be initialized to ”void” or some value. On the other hand, that would then also need to be true for göobals, and I don’t know if this added requirement for statics is something that would be appreciated.