So I'm learning C. I'm trying to mess around on a web-based IDE called https://replit.com/languages/c .
I decided I would learn to code a counter function that goes from 1 to 100(using a for loop iterator). I did this successfully with the following code:
#include <stdio.h>
int main (void) {
for (int i = 1; i < 101; i++)
{
printf("%i\n", i);
}
}
This code does exactly what I wanted. So I decided to learn more and break the code. I removed the data argument "i" in the print statement and proceeded to run the code again to see what happens.
#include <stdio.h>
int main (void) {
for (int i = 1; i < 101; i++)
{
printf("%i\n"); <-- notice int variable i is removed
}
}
Unsurprisingly, the console gave me a warning "warning: more '%' conversions than data arguments". This made perfect sense to me. What doesn't make sense is the output. The code ran with the warning and spit out the following in the console:
-921955384
0
0
0
0
0
...
I'm assuming it printed 99 more 0's after the large negative integer in question, and then terminated. I did not count all the 0's. Why the negative integer?
When I ran the program again, it printed:
1818314744
0
0
0
0
0
...
A third run prints the following:
-725290120
0
0
0
...
Fourth:
clang-7 -pthread -lm -o main
/usr/bin/../lib/gcc/x86_64-linux-gnu/8/../../../x86_64-linux-gnu/crt1.o: In function `_start':
(.text+0x20): undefined reference to `main'
clang-7: error: linker command failed with exit code 1 (use -v to see invocation)
exit status 1
So my question is: Why does it output the negative integer? Why is it changing/incrementing from positive to negative until its too big for it's integer type? Why all the 0's if there's not a data argument for my "%"? Why the error?
It seems like it has to do storage size and respective value ranges given a specific integer type. I got this info from CS50 and the Integer Type table at https://www.tutorialspoint.com/cprogramming/c_data_types.htm ... So I changed the code in the for loop to a Long integer type:
#include <stdio.h>
int main (void) {
for (long i = 1; i < 101; i++)
{
printf("%i\n");
}
}
It never errors out, so I thought I was onto something. But when I go BACK to int integer type to recreate the initial error on the 4th run, it never shows that error message from the fourth time I ran it. It keeps going. In fact it actually shows me a different initial integer... It started with 885981032(different number from first time around which was a negative number), then gave me -1940014968, then -42383224, then 1313794568, then 1348629208, then -303298488.... No error message... All using normal int type and not long.
What in the world is going on with this output? Why could I not recreate the error when going back to int? Fourth run just kept showing more numbers as opposed to the first time it spit out an error on the fourth run. What are the negative numbers? How are they incrementing? Why the 99 0's?
I'm just very curious as to what's going on behind the scenes here.