0

I have this C program:

#include <stdio.h>

int main(void)
{
    int a = 4;
    short b;
    double c;
    int* ptr;

    /* example of sizeof operator */
    printf("Line 1 - Size of variable a = %d\n", sizeof(a));
    printf("Line 2 - Size of variable b = %d\n", sizeof(b));
    printf("Line 3 - Size of variable c = %d\n", sizeof(c));

    /* example of & and * operators */
    ptr = &a; /* 'ptr' now contains the address of 'a'*/
    printf("value of a is %d\n", a);
    printf("*ptr is %d.\n", *ptr);

    /* example of ternary operator */
    a = 10;
    b = (a == 1) ? 20 : 30;
    printf("Value of b is %d\n", b );
    b = (a == 10) ? 20 : 30;
    printf("Value of b is %d\n", b );
}

which produces the expected output, but also produces the compiler error message:

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

three times, pointing to the " before 'Line x' in the printf statements. What is going on here?

Paul
  • 1,630
  • 1
  • 16
  • 23
  • Try `printf("Line 1 - Size of variable a = %d\n", (int)sizeof(a) );`. It's likely that `sizeof` on your machine is returning `unsigned long`. – Steve Summit May 11 '18 at 03:51
  • 1
    Oh no! The users have become *self aware!* – Mateen Ulhaq May 11 '18 at 03:51
  • Well, Wikipedia claims, "Self-awareness is the capacity for introspection and the ability to recognize oneself as an individual separate from the environment and other individuals. It is not to be confused with consciousness in the sense of qualia." – Mateen Ulhaq May 11 '18 at 03:53

2 Answers2

1
warning: format '%d' expects argument of type 'int', but argument 2 

has type 'long unsigned int' [-Wformat=]

This is a warning message, not an error message. This means the compiler has spotted something that looks like a mistake, but it's still able to compile the program.

In this case, it's spotted that you're using the wrong format specifier (% thingy) for the argument you're passing to printf. It should be %zu, since sizeof "returns" a size_t.

user253751
  • 57,427
  • 7
  • 48
  • 90
  • Traditionally, C compilers in their default configuration report many "errors" (i.e. severe violations of language rules) as "warnings". For which reason it is not really possible to dismiss diagnostic messages just because they are reported as "warnings". – AnT stands with Russia May 11 '18 at 04:21
0

Because sizeof() is not returning an int but size_t (in your case it defines as long unsigned int) and %d format expects an int argument, that's why there is a warning.

if you do (int) sizeof(a) it should go away

Ken.C
  • 41
  • 1