Skip to content
Advertisement

C: Why passing a float/double literal for an int argument does not raise warnings?

Consider this code:

#include <unistd.h>

int main(void) {
    sleep(.1);
    return 0;
}

I compile it with gcc -Wall sleep.c -o sleep with no warnings. Running it gives me

time ./sleep

real    0m0,001s
user    0m0,001s
sys     0m0,000s

.1 magically becomes 0, but my question is why no warnings? I’m using stock gcc 7.3.0 in Lubuntu 18.04

Advertisement

Answer

It’s a valid conversion – the fractional part is discarded when you convert it 0.1 to unsigned int. It’s essentially equivalent to sleep(0);. So a compiler is not required to issue any diagnostics.

However, gcc does have an option -Wconversion which produces:

gcc -Wall -Wextra -pedantic -Wconversion a.c

    a.c: In function ‘main’:
    a.c:8:11: warning: conversion from ‘double’ to ‘unsigned int’ changes value from ‘1.0000000000000001e-1’ to ‘0’ [-Wfloat-conversion]
         sleep(0.1);
               ^~~
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement