syntax - How are if statements in C syntactically unambiguous? -
i don't know whole lot c, understand basics , far can tell:
int main() { if (1 == 1) printf("hello world!\n"); return 0; }
and
int main() { if (1 == 1) printf("hello world!\n"); return 0; }
and
int main() { if (1 == 1) { printf("hello world!\n"); } return 0; }
are precisely syntactically equivalent. statement true; string printed; braces (apparently) optional.
sometimes, here on so, see following:
int main() { if (1 == 1) printf("one one\n"); printf("is inside if statement??/who kn0ws\n"); return 0; }
by power vested in codegolf, have been led believe c whitespace-agnostic; lexical analyser breaks tokens component parts , strips whitespace outside strings.
(i mean, whole reason semicolons-on-every-statement-thing parser can strip \n
, \t
, literal spaces , still know each statement ends, right??)
so how possible unambiguously parse previous bit of code (or perhaps can come better example of mean), if whitespace disregarded?
if c programmers want write in whitespace-dependent pythonic syntax, why write c, , why taught wherever c taught it's okay write lexically ambiguous (both me, programmer, , computer) statements this?
if (1 == 1) printf("one one\n"); printf("is inside if statement??/who kn0ws\n");
the second printf()
should never execute inside if
statement.
the reason being previous line ends semicolon, indicates end of if-block execute.
(i mean, whole reason semicolons-on-every-statement-thing parser can strip \n, \t, literal spaces , still know each statement ends, right??)
so how possible unambiguously parse previous bit of code (or perhaps can come better example of mean), if whitespace disregarded?
parsing example:
if (1 == 1)
// if - ( , ) - statements (or block) follow, skip whitespace
// no { found -> single statement, scan until ; (outside quotes / comments)
printf("one one\n");
// ; encountered, end of if-block
without braces, 1 statement belongs if-block.
but, said already, it's habit use braces. if later add statement (a quick temporary printf()
example), inside block.
special case:
int = 0; while(i++ < 10); printf("%d", i);
here printf()
execute once. mark ; @ end of while()
.
in case of empty statement, it's better use:
while(i++ < 10) ;
to make intention clear (or, alternative, empty block {}
can used well).
Comments
Post a Comment