0

Plz See

#include<stdio.h>  
#define TOTAL_ELEMENTS (sizeof(array) / sizeof(array[0]))
  int array[] = {23,34,12,17,204,99,16};


  int main()
  {
    
	  if(-1<= (TOTAL_ELEMENTS-2) )
		  printf("%s","gotcha\n");
	  else
		  printf("%s","oops\n");
    return 0;
  }

why is it printing oops

2
Contributors
5
Replies
6
Views
11 Years
Discussion Span
Last Post by SpS
0

>why is it printing oops
Probably because you're mixing signed and unsigned types using negative values. That way lies madness.

0

>why is it printing oops
Probably because you're mixing signed and unsigned types using negative values. That way lies madness.

You mean to say
compiler is taking -1 as signed and TOTAL_ELEMENTS as unsigned

0

Or since sizeof operator evaluates to unsigned numbers

Is that the reason

0

>compiler is taking -1 as signed and TOTAL_ELEMENTS as unsigned
No, I mean to say that -1 is being promoted to an unsigned type, which wraps the value around to the largest value representable by that unsigned type. Thus, -1 when promoted to an unsigned type is larger than the number of elements in the array.

Long story short, don't mix signed and unsigned types unless you know what's going to happen.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.