flying_loaf_3
flying_loaf_3

Reputation: 422

C Unexpected Identifier - For Loop Increment

Not sure what I've done here (pretty new to C, have done some Python, Arduino and Java before).

int main(void){
    unsigned long int sum = 0;
    unsigned int count = 0;
    for(unsigned long int i = 1; i <= 100; i++)
        if(i%3 != 0 && i%5 != 0)
            printf("cond%d\n", i);
            count++;
            sum += i; // $$here$$
    return 0;

When I compile the code, I get 'error undefined identifier: i' on line 10 (indicated with $$here$$

Upvotes: 2

Views: 87

Answers (1)

Eric Postpischil
Eric Postpischil

Reputation: 222352

C does not use indentation to structure program control (such as to indicate that more-indented statements are controlled by a less-indented statement above them). To group statements under the control of an if or other statement, you must use braces:

        if(i%3 != 0 && i%5 != 0)
        {
            printf("cond%d\n", i);
            count++;
            sum += i;
        }

The compiler error occurs because, due to the lack of braces, the scope of the for statements ends after the printf statement. So no declaration for i is visible at the sum += i; line, and the compiler complains.

The compiler will ignore most indentation and white space. When authors use indentation in C source code, it is to aid humans, not the compiler.

(C grammar does not require any braces around the if statement to keep it within the for statement’s control, because the if statement and the following lines form a single statement, once braces are added as shown above. However, many people would add braces just around the if statement to illustrate explicitly that it forms the body of the for statement. I treat this contextually, judging what is clearer in each situation.)

Upvotes: 3

Related Questions