1

Sometimes I just get so confused about the syntax in C. In struct, everything is separated by a semicolon and there is one extra semicolon after the last member, while in enum, everything is separated by a comma and there is no extra comma at the end. I always forget the last semicolon in struct since it doesn't seem to make sense to me. Is there any good reason for designing it that way? I hope someone can point out why it is good so that I can get used to it, right now it makes the syntax really hard to memorize.

Xufeng
  • 6,452
  • 8
  • 24
  • 30

2 Answers2

4

Perhaps the simplest way to memorize this is that structs and unions are basically nested scopes. They contain declarations, just lie functions or your "root" document (in global scope).

So, you declare struct members:

struct {
    int member_a;
    int member_b;
} ;

Kind of like how you declare globals or function members:

/* START OF FILE */
int global_a;
int global_b;
/* END OF FILE */

Enums are lists -- kind of like array declarations, or multiple variables, etc...:

int arr[] = {1, 2, 3}; //* see note below
enum Foo { FOO, BAR, BAZ };
int foo, bar, baz;

// multiple "sub-statements" in one statement
// note that this is generally considered bad practice.
foo++, bar++, baz = bar;

Or you could simply remember it this way: Semicolons are statement terminators (they end statements), while commas are separators (they come between elements).

(*note: arrays are an exception in that they optionally allow for a trailing comma. As to why they allow for that in arrays while they don't allow it for enums is beyond me)

Tim Čas
  • 10,501
  • 3
  • 26
  • 32
  • 2
    +1, since c99 a trailing `,` after the last enum constant is allowed. – ouah Feb 23 '14 at 22:12
  • In GNU C (and C++) (used by clang and GCC), a trailing comma definitely is allowed for an enum. I haven't actually looked at the standard, so I'm not sure if that's an extension or not. – Richard J. Ross III Feb 23 '14 at 22:13
  • @ouah: Really? I thought it was C11 that added that, not C99. – Tim Čas Feb 23 '14 at 22:13
  • @RichardJ.RossIII -- it's allowed, but the compiler tends to complain about it (with a warning). I'm not sure which `-W` enables that, but I think it's one of the warnings enabled with `-Wall`. – Tim Čas Feb 23 '14 at 22:14
  • @TimČas according to [this](http://stackoverflow.com/questions/792753/is-the-last-comma-in-c-enum-required), it was in fact C99. – Richard J. Ross III Feb 23 '14 at 22:14
  • @RichardJ.RossIII: Neat. Still doesn't explain why it wasn't allowed in C89 though. *shrug* – Tim Čas Feb 23 '14 at 22:15
3

In C:

  • A comma is a seperator. Between values. Example: enum.
  • A semicolon is a terminator. of Statements and declerations.
Elazar
  • 20,415
  • 4
  • 46
  • 67