why printf("%d", arg) works with arg of type int, short, char

J

Joe keane

%f takes double.

how about this?

@ cat bars.c
#include <stdio.h>


int main(int argc, char **argv)
{
char ac = 1;
short as = 1;
int ai = 1;
long int al = 1;
long long int aq = 1;
float af = 1;
double ad = 1;
long double ax = 1;

printf("c%d\n", sizeof (ac + ac));
printf("s%d\n", sizeof (as + as));
printf("i%d\n", sizeof (ai + ai));
printf("l%d\n", sizeof (al + al));
printf("q%d\n", sizeof (aq + aq));
printf("f%d\n", sizeof (af + af));
printf("d%d\n", sizeof (ad + ad));
printf("x%d\n", sizeof (ax + ax));
return 0;
}
@ cc -o bars bars.c
@ ./bars
c4
s4
i4
l4
q8
f4
d8
x12
@ cat bar.c
#include <stdio.h>


void test(void)
{
int ai = 1;
long int al = 1;
long long int aq = 1;
float af = 1;
double ad = 1;
long double ax = 1;

printf("%d", ai);
printf("%ld", ai); /* line 14 */
printf("%d", al); /* line 15 */
printf("%ld", al);
printf("%Ld", al); /* line 17 */
printf("%ld", aq); /* line 18 */
printf("%Ld", aq);
printf("%f", af);
printf("%lf", af); /* OK */
printf("%f", ad); /* OK */
printf("%lf", ad);
printf("%Lf", ad); /* line 24 */
printf("%lf", ax); /* line 25 */
printf("%Lf", ax);
}
@ cc --version
cc (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3
Copyright (C) 2011 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

@ cc -c bar.c
bar.c: In function ‘test’:
bar.c:14:5: warning: format ‘%ld’ expects argument of type ‘long int’, but argument 2 has type ‘int’ [-Wformat]
bar.c:15:5: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘long int’ [-Wformat]
bar.c:17:5: warning: format ‘%Ld’ expects argument of type ‘long long int’, but argument 2 has type ‘long int’ [-Wformat]
bar.c:18:5: warning: format ‘%ld’ expects argument of type ‘long int’, but argument 2 has type ‘long long int’ [-Wformat]
bar.c:24:5: warning: format ‘%Lf’ expects argument of type ‘long double’, but argument 2 has type ‘double’ [-Wformat]
bar.c:25:5: warning: format ‘%lf’ expects argument of type ‘double’, but argument 2 has type ‘long double’ [-Wformat]
 
B

Barry Schwarz

how about this?

@ cat bars.c
#include <stdio.h>


int main(int argc, char **argv)
{
char ac = 1;
short as = 1;
int ai = 1;
long int al = 1;
long long int aq = 1;
float af = 1;
double ad = 1;
long double ax = 1;

printf("c%d\n", sizeof (ac + ac));

Since sizeof evaluates to type size_t which need not be int, the
second argument needs a cast or the conversion specifier should be
%zu.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,023
Latest member
websitedesig25

Latest Threads

Top