From: Keith.S.Thompson+u@gmail.com   
      
   Janis Papanagnou writes:   
   > On 2026-02-06 06:10, Keith Thompson wrote:   
   >> Bart writes:   
   >>   
   >>> If I compile this code with 'gcc -Wall -Wextra -Wpedantic':   
   >>>   
   >>> #include    
   >>>   
   >>> int main() {   
   >>> int a = -1;   
   >>> printf("%u", a);   
   >>> }   
   >>>   
   >>> it says nothing. The program displays 4294967295 instead of -1.   
   >   
   > Yes. You instruct 'printf' with '%u' to interpret and display it   
   > (the variable 'a') as unsigned. ('-1' is not an unsigned numeric   
   > representation.) - I wonder what you are thinking here.   
   >   
   >> The behavior is unsurprising. The lack of a warning is very mildly   
   >> inconvenient.   
   >   
   > Indeed unsurprising. And I even don't see any inconvenience given   
   > that even an initialized declaration of 'unsigned a = -1;' is not   
   > considered a problem in "C". I rather learned that to be a useful   
   > code pattern when programming in "C".   
      
   Sure, but the point is that the program has undefined behavior.   
      
   If you define `unsigned a = -1;`, the value of the initializer is   
   implicitly converted from int to unsigned, and the value of UINT_MAX   
   is stored in `a`. That's well defined.   
      
   Passing a argument of type int to printf with a "%u" format is   
   well defined if and only if the value of the argument is within   
   the ranges of both types (which is almost certainly equivalent to   
   it being non-negative). This is strongly implied prior to C23,   
   and guaranteed in C23. There is no implicit conversion; the int   
   is treated as if it were of type unsigned int. In practice, it's   
   almost certain to display the value of UINT_MAX unless the compiler   
   goes out of its way to do something else.   
      
   A warning would not be inappropriate -- and in fact clang version   
   21 does issue a warning with "-Weverything". (The warning refers to   
   "-Wformat", which by itself doesn't trigger the warning; that might   
   be a bug.)   
      
   --   
   Keith Thompson (The_Other_Keith) Keith.S.Thompson+u@gmail.com   
   void Void(void) { Void(); } /* The recursive call of the void */   
      
   --- SoupGate-Win32 v1.05   
    * Origin: you cannot sedate... all the things you hate (1:229/2)   
|