简体   繁体   中英

warning: format '%ld' expects argument of type 'long int', but argument 2 has type 'int'

Build log:

warning: format '%ld' expects argument of type 'long int', but argument 2 has type 'int'

Program:

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

int main()
{
    printf("Hello world!\n");///for a new line
    printf("Hello world ");///simple
    printf("enter some values = %d %d %f",54432,54,54.76474)
    printf("%d \n",232);///integer in new line
    printf("%f \n",21.322432);///decimal in new line
    printf("%ld \n",3809);///large integer in new line
    printf("%lf \n",432758575375735.24);///large float in new line

    return 0;
}

This is undefined behavior . The compiler warns you and then the printf tries to process sizeof(long int) bytes where you have provided it with an integer literal which is of size sizeof(int) bytes.

It expects sizeof(long int) bytes and now if sizeof(int)==sizeof(long) It's alright else it's Undefined Behavior.

Don't think that format specifier are similar to variables. long variable can hold values of an int . This doesn't go with the format specifiers.

A casting would solve the problem

printf("%ld \n",(long)3809);

From standard §7.21.6.1 (Formatted input/output functions)

[7] If a conversion specification is invalid, the behavior is undefined. If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.

Integer constants have type int by default. The "%ld" format specifier expects a long int . Using the wrong format specifier invokes undefined behavior.

You need to add the L suffix for an integer literal to have type long :

printf("%ld \n",3809L);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM