3 ms·
I apologize for the stupidity of my question but shouldn't that be for(y=0; y<ymax; y++) { for(x=0; x<xmax; x++) { //... } } ?
by noobie 11y ago
I apologize for the stupidity of my question but shouldn't that be
for(y=0; y<ymax; y++)
{
for(x=0; x<xmax; x++)
{
//...
}
}
?
Edit: Oh, I get it, {} are only "mandatory" if we have more than one instruction, the second for loop gets counted as one instruction and hence the omitting of {}. Thanks!
- avar 11y agoNo, the two mean the same thing in C, e.g.: if (x) y; Is the same as: if (x) { y; }
- Macha 11y agoJust in case anyone who has never used C (or Java, or C# etc etc) is confused, it's not the indentation that is causing this meaning here: if (x) y; also has the same meaning.
- recursive 11y agoWhy would it be? Certainly not for readability. I think it was posted as intended.
- Sir_Cmpwn 11y agoIt works without the additional braces. Consider this: for (i=0;i<imax;i++) printf("%d\n", i); You can omit the braces if the body of the loop is a single block, just like an if statement. You can also do this: if (a == b) if (b == c) { do_thing(); } Same deal with the for loop. The nested loop is a single block.
- deleted 11y ago[deleted]
- halosghost 11y agoIn C, control flow like if, for, while, do, else, etc., take the rest of the line of code (i.e., till the next semi-colon) and runs it under the conditions of the clause. braces—{}—allow you to take multiple lines of code and have them be guarded at the same time rather than having to repeat the condition. GP is taking advantage of the fact that the next for clause will be considered a single statement, and therefore the second set of braces are not technically needed. However, omitting braces for single-line snippets has caused plenty of havoc in the past (cf. Apple's gotofail). Some would say it is better to always include braces in control flow.
- jimrandomh 11y agoIf I were doing it that way, I wouldn't give the outer blocks' curly braces their own lines. For example in C#, where pretty much every file has a single "namespace" block containing a single "class" block, I write it as: namespace SomeNamespace { class SomeClass { //... }} Which avoids having shifted the whole file an extra indent level to the right. But I haven't seen anyone else doing this.
- Avshalom 11y agoI'm not writing C# but yeah: AS3 and Java both have the Package{class{ two-step before you actually write any code. I don't even indent inside class: package{ class{ main{ now we indent } }}
- threeseed 11y agoYou don't indent after a package e.g. https://github.com/apache/spark/blob/master/core/src/main/java/org/apache/spark/JavaSparkListener.java https://github.com/apache/spark/blob/master/core/src/main/ja... And it's fair enough to indent with a main since it is so infrequent. Ideally you only have one main entry point.