473,608 Members | 2,479 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Portable way to printf() a size_t instance


Hello,

I have code which makses use of variables of type size_t. The code is
originally developed on a 32 bit machine, but now it is run on both a
32 bit and a 64 bit machine.

In the code have statements like this:

size_t buffer_size;
printf("Total buffer size: %ud bytes \n",buffer_size );

Now the format "%ud" works nicely on the 32 bit computer; it actually
works on the 64 bit computer as well, but the compiler spits out
warning message. On the 64 bit computer it would have prefered:

printf("Total buffer size: %uld bytes \n",buffer_size ); /* Or udl? */

As I said it works, but I would really prefer the program to compile
without warnings, as it is now I get *many* warnings of the type

file.c:line: warning: unsigned int format, different type arg (arg 1).

And, on several occasion this has actually led me to miss more
important warnings.
Any tips appreciated.
Joakim
--
Joakim Hove
hove AT ift uib no /
Tlf: +47 (55 5)8 27 90 / Stabburveien 18
Fax: +47 (55 5)8 94 40 / N-5231 Paradis
http://www.ift.uib.no/~hove/ / 55 91 28 18 / 92 68 57 04
Nov 14 '05 #1
25 36504
Joakim Hove wrote:

Hello,

I have code which makses use of variables of type size_t. The code is
originally developed on a 32 bit machine, but now it is run on both a
32 bit and a 64 bit machine.

In the code have statements like this:

size_t buffer_size;
printf("Total buffer size: %ud bytes \n",buffer_size );

Now the format "%ud" works nicely on the 32 bit computer; it actually
works on the 64 bit computer as well, but the compiler spits out
warning message. On the 64 bit computer it would have prefered:

printf("Total buffer size: %uld bytes \n",buffer_size ); /* Or udl? */

As I said it works, but I would really prefer the program to compile
without warnings, as it is now I get *many* warnings of the type

file.c:line: warning: unsigned int format, different type arg (arg 1).

And, on several occasion this has actually led me to miss more
important warnings.

Any tips appreciated.


For C89, convert to long unsigned.

printf("sizeof( int) is %lu\n", (long unsigned)sizeof (int));

--
pete
Nov 14 '05 #2
Joakim Hove wrote:
Hello,

I have code which makses use of variables of type size_t. The code is
originally developed on a 32 bit machine, but now it is run on both a
32 bit and a 64 bit machine.

In the code have statements like this:

size_t buffer_size;
printf("Total buffer size: %ud bytes \n",buffer_size );

Now the format "%ud" works nicely on the 32 bit computer;
It shouldn't. The %<qualifier>d are the conversion specifiers for signed
integers; the %<qualifier>u are the conversion specifiers for unsigned
integers. 'u' is not a qualifier for %d.

it actually
works on the 64 bit computer as well, but the compiler spits out
warning message.
Something like "%ud doesn't mean anything"?
On the 64 bit computer it would have prefered:

printf("Total buffer size: %uld bytes \n",buffer_size ); /* Or udl? */


I doubt it. The printf routine rarely "wants" meaningless specifiers.
If you have an up-to-date library, you could use
printf("Total buffer size: %zu bytes \n",buffer_size );

Otherwise, try
printf("Total buffer size: %lu bytes \n",
(long unsigned)buffer _size);
or
printf("Total buffer size: %llu bytes \n",
(long long unsigned) buffer_size);

That is, use an (properly written) unsigned specifier and cast the
size_t argument to the same size unsigned.
Nov 14 '05 #3
Martin Ambuhl wrote (and now clarifies):
Joakim Hove wrote: [...]
Now the format "%ud" works nicely on the 32 bit computer;

It shouldn't. The %<qualifier>d are the conversion specifiers for signed
integers; the %<qualifier>u are the conversion specifiers for unsigned
integers. 'u' is not a qualifier for %d.


I should have been clearer. "%u" is the specifier you are using. The
"d" is a literal portion of the output string. See the example below
and note the extra 'd' at the end of the string:

#include <stdio.h>
int main(void)
{
printf("Printin g an unsigned value using %%ud: %ud\n", 5u);
return 0;
}

Printing an unsigned value using %ud: 5d
Nov 14 '05 #4
Joakim Hove <ho**@ift.uib.n o> writes:
I have code which makses use of variables of type size_t. The code is
originally developed on a 32 bit machine, but now it is run on both a
32 bit and a 64 bit machine.

In the code have statements like this:

size_t buffer_size;
printf("Total buffer size: %ud bytes \n",buffer_size );
I think you mean "%u", not "%ud". "%d" is for (signed) int; "%u" is
for unsigned int.
Now the format "%ud" works nicely on the 32 bit computer; it actually
works on the 64 bit computer as well, but the compiler spits out
warning message. On the 64 bit computer it would have prefered:

printf("Total buffer size: %uld bytes \n",buffer_size ); /* Or udl? */


The format for unsigned long is "%lu".

In C90, the best way to print a size_t value is to convert it
to unsigned long and use "%lu":

printf("Total buffer size: %lu bytes\n", (unsigned long)buffer_siz e);

C99 adds a 'z' modifier specifically for size_t:

printf("Total buffer size: %zu bytes\n", buffer_size);

but many printf implementations don't support it. (Even if your
compiler supports C99 and defines __STDC_VERSION_ _ appropriately,
that's not, practically speaking, a guarantee that the library also
conforms to C99.)

Even in C99, the "%lu" method will work unless size_t is bigger than
unsigned long *and* the value being printed exceeds ULONG_MAX, which
is unlikely to happen in practice.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 14 '05 #5
Me
%z is the specifier for size_t in C99 but I assume you want to be
backwards compatible with older and broken implementations . Here is the
smart way to go about this (untested, use at your own risk):

#if __STDC_VERSION_ _ >= 199901L

#include <stdint.h>

#else

#include <limits.h>

#ifdef LLONG_MAX
typedef long long intmax_t;
typedef unsigned long long uintmax_t;
#define INTMAX_MIN LLONG_MIN
#define INTMAX_MAX LLONG_MAX
#define UINTMAX_MAX ULLONG_MAX
#elif defined(_I64_MA X)
typedef __int64 intmax_t;
typedef __uint64 uintmax_t;
#define INTMAX_MIN _I64_MIN
#define INTMAX_MAX _I64_MAX
#define UINTMAX_MAX _UI64_MAX
#else
typedef long intmax_t;
typedef unsigned long uintmax_t;
#define INTMAX_MIN LONG_MIN
#define INTMAX_MAX LONG_MAX
#define UINTMAX_MAX ULONG_MAX
#endif

#endif

or something similar for an implementation specific [u]intmax_t type
somewhat portably defined. There are several ways to do the next part
but here is one simple way is to create another implementation specific
header file:

#if __STDC_VERSION_ _ >= 199901L

#include <inttypes.h>

#else

#ifdef LLONG_MAX
#define PRIiMAX "%lli"
#define PRIuMAX "%llu"
#elif defined(_I64_MA X)
#define PRIiMAX "%I64i"
#define PRIuMAX "%I64u"
#else
#define PRIiMAX "%li"
#define PRIuMAX "%lu"
#endif

#endif

And for all your printf calls do:

printf("Total size: " PRIuMAX " bytes\n", (uintmax_t)size );

Another simple way is to create printf specifier for size_t similar to
the above using another implementation specific header that you have to
keep in sync with: "%z" for C99, "%Iu" for visual studio's runtime,
etc. or however you want to go about doing it.

Nov 14 '05 #6
On Sun, 12 Jun 2005 08:07:07 +0200, Joakim Hove
<ho**@ift.uib.n o> wrote:
I have code which makses use of variables of type size_t. The code is
originally developed on a 32 bit machine, but now it is run on both a
32 bit and a 64 bit machine.

In the code have statements like this:

size_t buffer_size;
printf("Total buffer size: %ud bytes \n",buffer_size );
That is undefined, because %u expects an int. Quite why you want to
print a 'd' after the number I don't know, but it's your choice...
Now the format "%ud" works nicely on the 32 bit computer; it actually
works on the 64 bit computer as well, but the compiler spits out
warning message. On the 64 bit computer it would have prefered:

printf("Total buffer size: %uld bytes \n",buffer_size ); /* Or udl? */
You probably mean %lu -- but it's still undefined behaviour because
size_t is not the same as an unsigned long except by accident (well,
implementers' choice, but something over which you have no control and
the next version of the compiler could change it).
As I said it works, but I would really prefer the program to compile
without warnings, as it is now I get *many* warnings of the type

file.c:line: warning: unsigned int format, different type arg (arg 1).
Heed them. Your code is incorrect. Try, for instance,

size_t buffer_size = 123;
printf("%u %d\n", buffer_size, 42);

On the 32 bit machine it may work (and give "123 42"), but on the 64 bit
machine it may give you something like "123 0" (or possibly "0 123", or
some other strange result).
And, on several occasion this has actually led me to miss more
important warnings.


So correct the printf code.

If your library is C99 compliant you can use the z conversion specifier
for size_t:

printf("%zu\n", buffer_size);

Note that the /library/ must be compliant, not the actual compiler, and
since gcc for instance uses printf from the underlying system it may not
be supported (as I recall it was on Linux but wasn't on Solaris when I
tried it). If the compiler doesn't support it then you may still get
warnings, of course.

Alternatively, cast the size to a known and supported type. For most
purposes long is sufficient:

printf("%lu\n", (long)buffer_si ze);

That will get rid of the warnings (because there is no longer any
mismatch) and allow for at least 32 bit sizes even on 16 bit machines.

Chris C
Nov 14 '05 #7
Keith Thompson wrote:
Joakim Hove <ho**@ift.uib.n o> writes:
I have code which makses use of variables of type size_t. The
code is originally developed on a 32 bit machine, but now it is
run on both a 32 bit and a 64 bit machine.

In the code have statements like this:

size_t buffer_size;
printf("Total buffer size: %ud bytes \n",buffer_size );


I think you mean "%u", not "%ud". "%d" is for (signed) int; "%u"
is for unsigned int.
Now the format "%ud" works nicely on the 32 bit computer; it
actually works on the 64 bit computer as well, but the compiler
spits out warning message. On the 64 bit computer it would have
prefered:

printf("Total buffer size: %uld bytes \n",buffer_size ); /* Or udl? */


The format for unsigned long is "%lu".

In C90, the best way to print a size_t value is to convert it
to unsigned long and use "%lu":

printf("Total buffer size: %lu bytes\n", (unsigned long)buffer_siz e);

C99 adds a 'z' modifier specifically for size_t:

printf("Total buffer size: %zu bytes\n", buffer_size);

but many printf implementations don't support it. (Even if your
compiler supports C99 and defines __STDC_VERSION_ _ appropriately,
that's not, practically speaking, a guarantee that the library
also conforms to C99.)

Even in C99, the "%lu" method will work unless size_t is bigger
than unsigned long *and* the value being printed exceeds ULONG_MAX,
which is unlikely to happen in practice.


I was going to reply to the OP, but this covers it better. The
major point is that, for C89 or any lack of full printf C99
coverage in the library, you have to cast the size_t operand to
something, and you have to then make the specifier agree with that
cast. The programmer probably knows how bit his size_t object can
actually become, and so can make the decision about what to cast it
to. The safest is the largest unsigned that the library can
handle.

--
"If you want to post a followup via groups.google.c om, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson
Nov 14 '05 #8
Chris Croughton wrote:
Alternatively, cast the size to a known and supported type. For most
purposes long is sufficient:

printf("%lu\n", (long)buffer_si ze);


ITYM

printf("%lu\n", (unsigned long)buffer_siz e);

--
ade ishs

Nov 14 '05 #9
Chris Croughton <ch***@keristor .net> writes:
On Sun, 12 Jun 2005 08:07:07 +0200, Joakim Hove
<ho**@ift.uib.n o> wrote:
I have code which makses use of variables of type size_t. The code is
originally developed on a 32 bit machine, but now it is run on both a
32 bit and a 64 bit machine.

In the code have statements like this:

size_t buffer_size;
printf("Total buffer size: %ud bytes \n",buffer_size );


That is undefined, because %u expects an int. Quite why you want to
print a 'd' after the number I don't know, but it's your choice...

[...]

I think it's only potentially undefined. If size_t happens to be
unsigned int for a given implementation, it's well defined. If you
use a "%u" format, the implementation doesn't care whether you
actually know that the argument is an unsigned int, or you just got
lucky.

It is, of course, unnecessarily non-portable.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 14 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

29
17546
by: whatluo | last post by:
Hi, c.l.cs I noticed that someone like add (void) before the printf call, like: (void) printf("Timeout\n"); while the others does't. So can someone tell me whether there any gains in adding (void) to printf. Thanks, Whatluo.
14
2845
by: Turner, GS \(Geoff\) | last post by:
Out of curiosity, why do programmers insist that the following piece of code printf("%d", 10); is wrong and should be printf("%d\n", 10); It's application specific, isn't it? GST
27
2958
by: jacob navia | last post by:
Has anyone here any information about how arrays can be formatted with printf? I mean something besides the usual formatting of each element in a loop. I remember that Trio printf had some extensions but I do not recall exactly if they were meant for arrays. Thanks
131
6093
by: pemo | last post by:
Is C really portable? And, apologies, but this is possibly a little OT? In c.l.c we often see 'not portable' comments, but I wonder just how portable C apps really are. I don't write portable C code - *not only* because, in a 'C sense', I
4
3682
by: Everton | last post by:
The task at hand is to initialize a variable of type "struct in6_addr" in a portable way. For instance: /* NetBSD - /usr/include/netinet6/in6.h */ struct in6_addr { union { __uint8_t __u6_addr8; __uint16_t __u6_addr16; uint32_t __u6_addr32; } __u6_addr; /* 128-bit IP6 address */
10
5313
by: riva | last post by:
This is an interview question from: http://www.freshersworld.com/interview/technical_interview_C.htm Can You write a function similar to printf() ? I can only think using putchar() and casting for such a thing.
5
1728
by: lithiumcat | last post by:
Hi, I was wondering whether there is a standard-compliant way to extend printf with a new %code that is not yet reserved (e.g. %r) with a given argument type. My guess would be to write a function that looks like « int my_printf(const char *fmt, ...); », with a special processing of fmt to replace the new %code with the correct data, and then hand over the processed fmt and the remaining arguments to vprintf.
43
366
by: Jrdman | last post by:
someone has an idea on how the printf function is programmed ?
0
8059
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8495
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8330
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6815
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6011
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5475
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4023
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2474
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
0
1328
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.