3 ms·
What is the “correct” version of this?
by shoto_io 6y ago
What is the “correct” version of this?
- flohofwoe 6y agoJust split them into separate variable definitions: int i1 = 1; int i2 = 2; The "usual footgun" is: int i1, i2, i3 = 0; Only i3 will be initialized in this case. And since one needs to write out the assignments anyway, adding the type for each variable doesn't hurt either. (today's compilers usually have uninitialized-warnings for this though, but sometimes people forget to add a -Wall to their compiler options, especially beginners, and then get stuck on such trivial problems).
- thrwaeasddsaf 6y agoSorry I can't read your comment, could you split your words into separate paragraphs?
- sltkr 6y agoThere is nothing incorrect about multiple declarations, but the syntax can become confusing when declaring pointers or arrays: char *s = "foo", *t = "bar"; A beginner might forget to add the asterisk in `*t` (especially if the first declaration is written `char*` with no space on the left of the asterisk). Similarly with multiple types: char *p = "foo", **q = &p, *z[2] = {"foo", "bar"}, *(*f)(const char*) = strdup; This is correct and an intermediate C programmer won't have too much trouble parsing these, but in the interest of clarity, it makes sense to put each declaration on a separate line. If you find yourself needing a lot of local variables, that's often a bad sign anyway, since it implies that the function has a lot of state to manage. In that case, you might want to rethink your implementation to make it less complex, or restructure the code to make it more managable.