How to stop GCC complaining about “directive output may be truncated” in snprintf() call?

后端 未结 1 1444
名媛妹妹
名媛妹妹 2020-12-11 22:49

I\'m using GCC 9.2.0 on both an ancient Linux (RedHat 5.2) and modern macOS 10.14.6 Mojave, and I get the same complaint on both.

#include 
#i         


        
相关标签:
1条回答
  • 2020-12-11 23:18

    With compilers that check the range of possible values, use % to quickly limit the range.

    % some_unsigned_N insures the output is in [0... N-1].

    Note that % some_pos_int_N output is in the (-N ...N) range so recommend unsigned math to avoid the '-' sign.

    snprintf(ex->mm_yyyy, sizeof(ex->mm_yyyy), "%d-%d", 
        //  tm->tm_mon + 1, tm->tm_year + 1900);
        (tm->tm_mon + 1)%100u, (tm->tm_year + 1900)/10000u);
    

    May also want to use "%u" should some_unsigned_N near INT_MAX.

    0 讨论(0)
提交回复
热议问题