EDIT:
I apologize for assuming this will be obvious, but "don't forget to ignore the warnings" was not to be taken seriously. In fact, I think this would be a reason alone to re-write the program.
Compile the following program (don't forget to ignore the warnings!):
#include <stdio.h>
int main ()
{
long int i;
long int j;
scanf("%d", &i);
scanf("%ld", &j);
printf("i == %ld\n", i);
printf("j == %ld\n", j);
return 0;
}
Run it and supply an integer higher than 2147483647 two times and you'll get your answers.
SPOILER:
I did this with 4294967297 and the following got printed out:
i == 1
j == 4294967297
Of course the answer is architecture specific and I assumed your machine stores int
in 32 bits. But if there's a reason to use long int
in order to store a number in it, you better use a length modifier (if it doesn't make a difference, you don't need to use a long int
).
But to answer your questions a bit more explicitly:
Does that mean that the length modifier alters the type of the assigned variable, if it is not actually matching to the format value defined with the conversion specifier?
No. As you saw when trying to store a value that should fit into a long int
without the length modifier will act as if you're storing into an int
(even behaving as if an overflow occurred). If you use %ld
with scanf
to try to store a value into an int
variable there's no segfault thrown, and this can lead to bad things. Compiling the following (and having to ignore the warning for the sake of the experiment):
#include <stdio.h>
int main ()
{
int k[2] = {0,0};
printf("k[0] == %d\n", k[0]);
printf("k[1] == %d\n", k[1]);
scanf("%ld", &k);
printf("k[0] == %d\n", k[0]);
printf("k[1] == %d\n", k[1]);
return 0;
}
and running it by inputting 4294968300 prints out:
k[0] == 0
k[1] == 0
4294968300
k[0] == 1004
k[1] == 1
meaning that the notorious scanf
has written past k[0]
into k[1]
completely unnoticed!
Why should I [sic] implement a length modifier in the statement exactly, whether I've [sic] already declared the assigning variable as, for example long int, proper or not?
I quite do not understand why I [sic] should do so and do not see any difference in the output between including it and doing it without length-modifier.
I think the examples above should give you a strong incentive to not ignore the warnings when trying to compile with mismatched length modifier in a scanf
call. Otherwise, you might be even running a security risk.