user4418808
user4418808

Reputation:

Syntactical Sour

Well there are just some weird syntax question thrown to you by some author of the books just to check the understanding of the syntax while I think these kind of weird syntax may not be used by any programmer but just for the sake of understanding, I would like to understand how the following for loop behaves and why the compiler doesn't throws any syntactical error

#include <stdio.h>

int main(void)
{
    short int i=0;
    for(i<=5&&i>=-1 ;++i; i>0)
      printf("%d",i);
    return 0;
}

Upvotes: 2

Views: 105

Answers (3)

Sourav Ghosh
Sourav Ghosh

Reputation: 134356

Ok, as per the for loop is concerned, the simplified syntax # is

for( run_this_once_at_start;  check_this_each_time;  run_this_after_each_iteration)

Credit: Mr. Matt

Compiler will only check for the matching syntax. Let's compare it with your code, which says

for(i<=5&&i>=-1 ;++i; i>0)

so, after breakdown,

  • run_this_once_at_start is i<=5&&i>=-1 Note
  • check_this_each_time is ++i
  • run_this_after_each_iteration is i>0

which all are valid expressions from the syntax point-of-view. So, compiler's happy, no warnings.

Note: to break down i<=5&&i>=-1, in C, <= has higher precedence over &&, so effectively, your code behaves like ((i<=5) && (i>=-1)) which is perfectly valid.

[#] - For a detailed idea, see this answer of mine.

Upvotes: 1

a_pradhan
a_pradhan

Reputation: 3295

The for statement has the following form :

for(expression; expression; expression);

The three expressions can be any valid expressions allowed in the C language. So the code is syntactically valid. However due to uninitialized variable, the behaviour will be undefined. Also, it is advisable to use int main(void) and return an exit code.

Starting with C99 and C11, declarations are also allowed in place of the first expressions making it a statement. Thus it is :

for(statement; expression; expression);

Upvotes: 2

M.M
M.M

Reputation: 141628

For loops are:

for( run_this_once_at_start;  check_this_each_time;  run_this_after_each_iteration)

The actual code in those three areas can be any expression at all so long as the second one is a expression that's a valid operand for the ! operator. The first one can even contain a declaration, in C99 and later.

In your example there are no syntax errors. The first and third conditions don't do what would be considered good style, however they are not illegal.

Upvotes: 2

Related Questions