J...S
J...S

Reputation: 5207

2 similar C programs with macro producing different output

The following code prints nothing:

#include<stdio.h>
#define TOTAL_SIZE ( (sizeof(array))/(sizeof(array[0])) )
int main()
{
    int array[]={1,2,3}, d;
    for(d=-1; d<=TOTAL_SIZE-2; ++d)
    {
        printf("%d\n", array[d+1]);
    }
    return 0;
}

d=-1 <=3-2
prints array[-1+1] which is array[0]
d=0 <=3-2
prints array[0+1] which is array[1]
d=1 <=3-2
prints array[1+1] which is array[2]

But not even a single element is printed!



But the this code produces the right output of printing all the elements in the array:

#include<stdio.h>
#define TOTAL_SIZE ( (sizeof(array))/(sizeof(array[0])) )
int main()
{
    int array[]={1,2,3}, d;
    for(d=0; d<=TOTAL_SIZE-1; ++d)
    {
        printf("%d\n", array[d]);
    }
    return 0;
}

But the net effect of both the loops seem to be the same.

If we replace the macro TOTAL_SIZE with the number of elements in the array, it works. So the problem appears to be with the macro.

But when I try to print the value generated by TOTAL_SIZE, it prints the correct value.

What is the problem with the first program?

Upvotes: 0

Views: 68

Answers (1)

Micha
Micha

Reputation: 96

The problem with your macro is that sizeof returns an size_t which is an unsigned integer type that you are comparing to a signed int. The solution is to cast your size to an int.

#define TOTAL_SIZE (int)( (sizeof(array))/(sizeof(array[0])) )

Upvotes: 8

Related Questions