Reputation: 1949
Why is snprintf giving different value in second case. Is it because any integer limit. Can you please explain how snprintf works and why the reason for that negative value
#include <stdio.h>
#include <string.h>
main()
{
char buff[256];
snprintf(buff,256,"%s %d"," value",1879056981);
printf("%s",buff);
}
output:
value 1879056981
#include <stdio.h>
#include <string.h>
main()
{
char buff[256];
snprintf(buff,256,"%s %d"," value",2415927893);
printf("%s",buff);
}
output:
value -1879039403
Upvotes: 0
Views: 299
Reputation: 121387
It's because the integer 2415927893
can't represented by any integer type on your system and you have signed overflow in your program.
The exact type of integer literal depends on how big the number is. C11 defines that an integer literal can be of int
or long int
or long long int
, depending on which one fits first in that order.
6.4.4.1 Integer constants
The type of an integer constant is the first of the corresponding list in which its value can be represented.
Turn on the compiler warnings.
On my system, gcc warns about it when I compile youre code with:
gcc -std=c11 -Wall -pedantic t.c
t.c:4:1: warning: return type defaults to ‘int’ [enabled by default]
t.c: In function ‘main’:
t.c:9:4: warning: format ‘%d’ expects argument of type ‘int’, but argument 5 has type ‘long long int’ [-Wformat]
t.c:9:4: warning: format ‘%d’ expects argument of type ‘int’, but argument 5 has type ‘long long int’ [-Wformat]
Upvotes: 1
Reputation: 9062
The literal 2415927893 is interpreded as an int. As it is larger than INT_MAX on your machine, you get an overflow.
To avoid this, you may interpret it as an unsigned int:
snprintf(buff,256,"%s %u"," value",2415927893U);
Or as long long:
snprintf(buff,256,"%s %lld"," value",2415927893ll);
Upvotes: 1