Link to home
Start Free TrialLog in
Avatar of prashant_n_mhatre
prashant_n_mhatre

asked on

Comma in Sting Array

What is the use of defining a string array as
char *str[]={"Good","Bye",} ;
What is the purpose of the comma after the last string?
Compiler compiles it without any warning or error.
Avatar of anup_s
anup_s

I think this means, there are 3 data string pointers in the above array, with the third one set to null.

- Anup
Permitting the final comma is just makes it easier to add elements or move them around. In the example above, the array of character pointers will actually only have two entries.
This:

char *str[]={"Good","Bye",} ;

and this:

char *str[]={"Good","Bye"} ;

are 100% equivalent and the compiler ignores the trailing ",".
Avatar of prashant_n_mhatre

ASKER

jhance,

The question is "Why does compiler ignore the comma?"
Simple:

Because the ANSI C and C++ LRM (Language Reference Manuals) say that it must.

But there must be some reason for this...
I'm not that much of a C historian but my take on this is because that's the way the original Kernighan and Ritchie C compiler worked and K&R "C" became quite widely used long before the standardization process began.

I've heard the defense that wkmat42 noted above but I don't think that would have been a good enough reason to put it in the spec.  This is undoubtedly one of those things what, if changed, would have broken a lot of existing C code and angered a lot of people.

As always in the standarization process, it's a lot of give and take and compromise between the early pioneers, the academic purists, and the commercial interests.
ASKER CERTIFIED SOLUTION
Avatar of coderat
coderat

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Not all compilers have always supported the extraneous comma. I can vaguely recall a time when compilers didn't support the use of an extraneous comma. When Java was released, I remember thinking it was really cool that it was part of its standards and thought we ought to have it too.

Of course it may have already been a part of the standard, but by then I had been brainwashed by all the compiler errors that told me to stop screwing it up. Even the compiler we were using on our AIX boxes was, until recently, old enough to lack support for it. But that's an even longer and more painful story.
Thanks all...