Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I print the size of int in C?

Tags:

c

I am trying to compile the below on RHEL 5.6 , 64 bit, and i keep getting a warning

"var.c:7: warning: format ‘%d’ expects type ‘int’, but argument 2 has type ‘long unsigned int’"

Here is my code:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    unsigned int n =10;
    printf("The size of integer is %d\n", sizeof(n));
}

It does not matter if i change the declaration for "n" to following

  1. signed int n =10;
  2. int n = 10;

All i want to do is print the size of integer on my machine, without really looking into limits.h.

like image 611
Jimm Avatar asked May 10 '11 00:05

Jimm


People also ask

How do I print an int size?

printf("The size of integer is %zu\n", sizeof(n)); To clarify, use %zu if your compiler supports C99; otherwise, or if you want maximum portability, the best way to print a size_t value is to convert it to unsigned long and use %lu . printf("The size of integer is %lu\n", (unsigned long)sizeof(n));

What is sizeof () in C?

The sizeof operator gives the amount of storage, in bytes, required to store an object of the type of the operand. This operator allows you to avoid specifying machine-dependent data sizes in your programs.


2 Answers

The sizeof function returns a size_t type. Try using %zu as the conversion specifier instead of %d.

printf("The size of integer is %zu\n", sizeof(n));

To clarify, use %zu if your compiler supports C99; otherwise, or if you want maximum portability, the best way to print a size_t value is to convert it to unsigned long and use %lu.

printf("The size of integer is %lu\n", (unsigned long)sizeof(n));

The reason for this is that the size_t is guaranteed by the standard to be an unsigned type; however the standard does not specify that it must be of any particular size, (just large enough to represent the size of any object). In fact, if unsigned long cannot represent the largest object for your environment, you might even need to use an unsigned long long cast and %llu specifier.

In C99 the z length modifier was added to provide a way to specify that the value being printed is the size of a size_t type. By using %zu you are indicating the value being printed is an unsigned value of size_t size.

This is one of those things where it seems like you shouldn't have to think about it, but you do.

Further reading:

  • printf and size_t
  • portable way to print a size_t instance
  • assuming size_t is unsigned long
like image 90
Robert Groves Avatar answered Sep 19 '22 12:09

Robert Groves


Your problem is that size_t is an unsigned type. Try using

printf("The size of integer is %u\n", sizeof(n));

and you should get rid of that warning.

like image 43
Aurojit Panda Avatar answered Sep 21 '22 12:09

Aurojit Panda