Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C Macro List size resolving but not entering for loop

I have the following code and when I try to use the sizeof list a as a condition in for loop it does not enter it, but if I hard code it, it enters the loop. Why is this behaviour happening?

#include <limits.h>
#include <malloc.h>
#include <stdio.h>

#define MY_VAL (sizeof(a) / sizeof(a[0]))
#define MY_NEW_VAL 5

int a[] = {1, 2, 3, 4, 5, 6, 7};

int main() {
  int i;
  for (i = -1; i <= (MY_VAL - 2); i++) {
    printf("In loop 1\n");
  }
  for (i = -1; i <= MY_NEW_VAL; i++) {
    printf("In loop 2\n");
  }
}

output –>

In loop 2
In loop 2
In loop 2
In loop 2
In loop 2
In loop 2
In loop 2

My compiler is clang version 15.0.7, running linux as my os. Just in case this is a compiler specific behaviour.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I am aware this is not something to be used in a real world use case, just found this behaviour to be odd. Please explain.

>Solution :

sizeof is of type size_t, which is unsigned, whereas your i is signed. C is converting i to a size_t, which makes the -1 a large positive number — greater than MY_VAL - 2. So the loop never runs. If you had had sufficient warnings enabled, the compiler would have told you about this possible problem.

MY_NEW_VAL on the other hand is an unspecified type, so C matches it to i. So that one works.

Since you want to start at -1, you need to make the limit signed: for (i = -1; i <= (int)MY_VAL - 2; i++). Then it works.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading