anavaras lamurep
anavaras lamurep

Reputation: 1493

For Loop condition

#include <stdio.h>
#define all_mem (sizeof(x) /sizeof(x[0]))
int x[] ={1,2,3,4,5,6,7,8,9,10};

     int main(void) {
            //  printf("The condition is %d",(all_mem-2));
            int i;
                for(i=-1;i<=(all_mem-2);i++)
            {
                printf("The number is %d",i);
            }
            return 0;
        }

In the above code for loop is not even executing for a single time, i tried printing condition and its satisfies for loop condition. Any insights how macro expression in for loop condition is evaluated to the value less than -1?

Upvotes: 1

Views: 171

Answers (2)

user3629249
user3629249

Reputation: 16540

after making a few corrections to the code, forinstance, sizeof() returns a size_t, not an int the code worked perfectly.

Here is the modified code:

#include <stdio.h>

#define all_mem (sizeof(x) /sizeof(x[0]))

int x[] ={1,2,3,4,5,6,7,8,9,10};

int main(void)
{
    printf( "all_mem = %ld\n", all_mem ); // << added for debugging

    //  printf("The condition is %d",(all_mem-2));
    int i;
        for(i=-1;i<=(int)(all_mem-2);i++) // << 
        // << properly cast to int
        // otherwise compiler raises warning and unsigned comparison made
    {
        printf("The number is %d\n",i);
    }
    return 0;
}

Here is the output from the above code:

all_mem = 10
The number is -1
The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
The number is 6
The number is 7
The number is 8

When compiling, always enable all the warnings, then fix those warnings.

If the above statement had been followed, then you would have seen the problem, without our help.

(for gcc, at a minimum use: -Wall -Wextra -pedantic and I also add: -Wconversion -std=c99)

Upvotes: 0

ShadowRanger
ShadowRanger

Reputation: 155323

The all_mem macro is returning a size_t value; integer promotion rules mean the comparison of i <= (all_mem - 2) is promoting i to a size_t, which means the value is huge, rather than -1. Try casting to ensure signed comparison:

for(i = -1; i <=(ssize_t)(all_mem- 2); ++i)

Upvotes: 2

Related Questions