0

I'm a student trying to learn C and C++, I've got a problem with the specifier %d I dont't understand the exception that is written in the console, It's writing

The format %d expects argument of type 'int', but argument 2 has type 'long long unsigned int' [-Wformat]

Here is the code :

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

int main()
{
    short int u=1;
    int v=2;
    long int w=3;
    char x='x';
    float y=4;
    double z=5;
    long double a=6;
    long b=7;
    printf("short int:%d\n",sizeof(u));
    printf("int:%d octets\n",sizeof(v));
    printf("long int:%d octets\n",sizeof(w));
    printf("char:%d octets\n",sizeof(x));
    printf("float:%d octets\n",sizeof(y));
    printf("double:%d octets\n",sizeof(z));
    printf("long double:%d octets\n",sizeof(a));
    printf("long:%d octets\n",sizeof(b));
    return 0;
}
Vlad from Moscow
  • 224,104
  • 15
  • 141
  • 268
  • 4
    the result of `sizeof` is of type `size_t`, which on your system is equivalent to a Long Long Unsigned. Instead of `%d`, you should use `%zu` which is meant for arguments of type `size_t`. – Christian Gibbons Feb 08 '21 at 18:08

2 Answers2

1

The type of the value returned by the operator sizeof is the unsigned integer type size_t The conversion specifier d is used to output values of the type int. You have to use the conversion specifier zu. Otherwise you will get undefined behavior.

For example

printf("short int:%zu\n",sizeof(u));

From the C Standard (7.21.6.1 The fprintf function)

9 If a conversion specification is invalid, the behavior is undefined.275) If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.

Vlad from Moscow
  • 224,104
  • 15
  • 141
  • 268
1

The sizeof operator returns a size_t type. This is always unsigned and, on your platform, is a long long unsigned int; on other platforms, it may be just unsigned long or, indeed, some other (unsigned) integer type.

Use the %zu format specifier for arguments of this type; this will work whatever the actual size_t type definition happens to be.

Adrian Mole
  • 30,672
  • 69
  • 32
  • 52