Path: csiph.com!news.bbs.nz!news.swapon.de!eternal-september.org!feeder.eternal-september.org!reader02.eternal-september.org!.POSTED!not-for-mail From: Keith Thompson Newsgroups: comp.lang.c Subject: Re: C++ features for C Date: Thu, 17 May 2018 14:13:49 -0700 Organization: None to speak of Lines: 54 Message-ID: References: <11edbfd7-461d-4579-8ac7-a9e84a6b7630@googlegroups.com> <87po1xi2n1.fsf@bsb.me.uk> <87k1s5hror.fsf@bsb.me.uk> Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Injection-Info: h2725194.stratoserver.net; posting-host="6dd19cd3091e1460a04414b367a948c0"; logging-data="5580"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX18QUur4XZMkTUs6apTXgJxh" User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/23.1 (gnu/linux) Cancel-Lock: sha1:NRBhEn9U49B4ScoeVrpNjcRZBTg= sha1:PQ0HvwGTwa7seZIl2ZCSLcthvBk= Xref: csiph.com comp.lang.c:130735 David Brown writes: > On 17/05/18 21:37, Keith Thompson wrote: >> David Brown writes: >>> On 17/05/18 18:07, Keith Thompson wrote: >> [...] >>>> And then you could write: >>>> >>>> long x = 42; >>>> printf("x = %d\n", x); [typo corrected] >>>> >>>> and never know that there's a potential problem until you port the code >>>> to another system. >>> >>> Correct. That is perfectly fine for most of my code. >> >> It's perfectly fine to have code whose behavior is undefined but that >> happens to work on your system, that could be made completely portable >> by using "%ld" rather than "%d"? >> >> I don't mind making non-portable assumptions now and then, but printf >> formats are so easy to get right that I take the (small) extra effort to >> do so. > > In a case where you have a type like "long" or "int" it is easy to get > it right - it's rare you need a warning there. > > The discussion was on types like "int32_t" which might be "int" and > might be "long" on a platform with 32-bit int /and/ 32-bit long. That > is when I would be happier writing "printf("%x = %d\n", x);" /or/ > "printf(%x = %ld\n", x);" regardless if int32_t happened to be "int" or > "long". That would mean that I would not get a warning in cases where I > had specifically picked "x" to be "long" and used it with "%d". That is > the price you have to pay for less strict warnings. (Usually I am a fan > of lots of strict warnings, but sometimes they get in the way.) gcc warns about format strings by default. You'd have to disable that warning explicitly. My solution: printf("x = %ld\n", (long)x); I know that long is wide enough to hold any value of type int32_t, and I know that "%ld" is the correct format for a long argument. (I *might* be lazy and use "%d" and (int) if I happen to know that int on the current system is at least 32 bits and/or that the value of x is small enough.) -- Keith Thompson (The_Other_Keith) kst-u@mib.org Working, but not speaking, for JetHead Development, Inc. "We must do something. This is something. Therefore, we must do this." -- Antony Jay and Jonathan Lynn, "Yes Minister"