-3

For example, when my code is as shown below, I get -1301113336 for a = 0 and -1266657529 for a = 1 to 99.

#include <stdio.h>

int main()
{
    int a;
    for (a = 0; a < 100; a++)
    {
        printf("\n%i");
    }
}

Is this some kind of undefined case when behaviour varies by compiler? If I use gcc, where do these numbers come from and why does it not change for each iteration?

O1G
  • 71
  • 1
  • 7
  • 1
    Put the newline at the end of the string. Putting it at the beginning is abnormal and will cause problems. But your real problem is you forgot to include `a` in the argument list. Your compiler should have warned you about it. – Tom Karzes May 03 '20 at 22:41
  • @TomKarzes Thanks but my question was not about why it does not print 'a' but rather what it prints then. To learn more about what happens behind the scenes... – O1G May 04 '20 at 10:27

2 Answers2

6

Read about the calling conventions of your implementation and about undefined behavior.

Practically speaking, what is printed could be the "random" content of some processor register mentioned in the ABI specifcation relevant to your implementation.

Fpr Linux/x86-64 see this and that.

If you use GCC as you C compiler, you could compile your foo.c code with gcc -S -fverbose-asm -Wall -O2 foo.c and look into the generated assembler code foo.s

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
5

If the number of arguments don't match what the format strings expects, or if a given argument is not the correct type for the corresponding format specifier, you invoke undefined behavior.

Using gcc without optimization on an x64 Linux machine, this is what you'll probably see:

Integer arguments to a function are typically pushed onto the stack. So a %i format specifier will look for sizeof(int) bytes on the stack. If you fail to pass in an argument, it will read whatever bytes happen to exist on the stack where the argument would have been.

dbush
  • 205,898
  • 23
  • 218
  • 273