5 ms·
Integer Conversions and Safe Comparisons in C++20
- titzer 4y agoVirgil has a family of completely well-defined (i.e. no UB) fixed-size integer types with some hard-fought rules that I eventually got around to documenting here: https://github.com/titzer/virgil/blob/master/doc/tutorial/FixedSizeIntegers.md https://github.com/titzer/virgil/blob/master/doc/tutorial/Fi... One of the key things is that values are never silently truncated (other than 2's-complement wrap-around that is built-in to arithmetic) or values changed; only promotions. The only sane semantics for over-shifts (shifts larger than the size of the type) is to shift the bits out, like a window. The upshot of all that is that Virgil has a pretty sane semantics for fixed-size integers, IMHO. Particularly comparisons. Comparing signed and unsigned ints is not UB and cannot silently give the wrong answer; integers are always compared on the same number line. It takes only a maximum of one extra comparison to achieve this. AFAICT this is what achieved by the std::cmp* referenced in the article.
- phoe-krk 4y agoLooking at horror stories like this along with their "solutions" that are done by slapping more standard functions on top of the already existing piles, I'm glad that I do my personal programming in languages which 1) have meaningful numeric towers and automatically do promotion/demotion as appropriate, 2) don't implicitly convert signed integers into unsigned integers and error out instead. With each standard revision, C++ is becoming more and more horrible as much as it strives to become a better and more useful language.
- GeorgeTirebiter 4y agoPray tell, what are your personal programming languages?
- phoe-krk 4y agoLisp and Erlang. The latter doesn't have a numeric tower but has automatic bigint conversion and handling. The former is eager to error upon signed/unsigned type violations once you specify them.
- jcelerier 4y ago> has automatic bigint conversion how can one implement this without a branch before literally any arithmetic operation?
- throwawaymaths 4y agoYou're not using Erlang for speed. You're using Erlang for reliability. (Note this is not the same thing as correctness or "safety")
- phoe-krk 4y agoIn CL, you can declare that you need modulo arithmetic, which will give you branchless arithmetic operations. In Erlang, you don't; the language was never made for that sort of speed.
- bitwalker 4y agoErlang checks for overflow after arithmetic ops are performed internally (IIRC), so you are generally only penalized when overflow actually occurs and requires promotion, which probably isn’t much different in performance from a language that would raise an error on overflow, though obviously not as efficient as a language that just wraps around on overflow.
- AlexSW 4y agoNot sure Erlang is strong on the basic types front on the whole though; I've never been a fan of strings in Erlang. Greatly prefer C++ on this front.
- bitwalker 4y agoErlang binaries on the other hand are awesome, and the use of lists in what Erlang refers to as chardata/iodata is really nice when generating data that will be written to some kind of output device, since no preprocessing is needed to convert the data to a flat array of bytes. Overall though, yeah, it plays pretty loose with types, though it is generally strict about not using integers where floats are expected and vice versa.
- kwant_kiddo 4y agoOnce again the comments prove that people are more interested in trash-talking C++ than than solving real problems. C++20 IS fixing many complaints or design-choices made in the past. In terms of the article it casually mentions in the end using '''-Werror -Wall -Wextra''' The unsigned signed comparisons will fail to compile. Most serious projects use these flags anyway. I wonder if clang-tidy will also catch this?
- phoe-krk 4y agoAs a person working on big C++ telco codebases for a living, I'm fully aware that C++ is solving real problems and that -Weverything makes it somewhat possible to work with the language. At the same time, I'm appalled by the negative consequences of the "let's fix problems with the old and broken comparison operator by introducing a new, better comparison operator, since we need to maintain almost complete backwards compatibility" approach that C++ takes here. I'm interested in solving real problems, but C++ deserves trash talking for this reason alone.
- rictic 4y agoWhat's the alternative? Change the semantics of the comparison operator so that code looks cleaner? That means that when you read a comparison in source you have to know how it's going to be compiled in order to tell if the code is correct or not.
- lifthrasiir 4y agoYou can opt in a new behavior, attribute syntax added in C++11 should make this much more bearable. In fact, I'm honestly surprised that this mode of language evolution didn't seem to be frequently discussed in C++ WG at all; ECMAScript had `use strict` which is very much the same thing and well received, and if ECMAScript can do it with a lot of legacy code, there is no real reason C++ can do the same.
- sharikous 4y ago
- lultimouomo 4y agoThe usual arithmetic conversions linked from the article [0] are a bit different from the ones I know. In particular, if int can represent all values of all operands, both of them will be converted to int. Thus comparing unsigned short and short will usually (if short is narrower than int) do the right thing. C++Insights (which I didn't know! This is the real pearl of this article.) agrees with me [1]. [0] https://en.cppreference.com/w/cpp/language/operator_arithmetic#Conversions https://en.cppreference.com/w/cpp/language/operator_arithmet... [1] https://cppinsights.io/lnk?code=I2luY2x1ZGUgPGNzdGRpbz4KCmludCBtYWluKCkKewogICAgc2hvcnQgYSA9IC0xOwogICAgdW5zaWduZWQgc2hvcnQgYiA9IDE7CiAgCiAgcHJpbnRmKCIlZCIsIGEgPCBiKTsKfQ==&insightsOptions=cpp17&std=cpp17&rev=1.0 https://cppinsights.io/lnk?code=I2luY2x1ZGUgPGNzdGRpbz4KCmlu...
- anonymoushn 4y agoThe relevant part of your first link seems to be right at the beginning: > If the operand passed to an arithmetic operator is integral or unscoped enumeration type, then before any other action (but after lvalue-to-rvalue conversion, if applicable), the operand undergoes integral promotion. Clicking "integral promotion" leads here: https://en.cppreference.com/w/cpp/language/implicit_conversion#Integral_promotion https://en.cppreference.com/w/cpp/language/implicit_conversi...
- CrendKing 4y agoIf there are already std functions "safe" for integral comparison, why not replace the < and > operators impl with those? Is it because it violates existing specs? If so, shouldn't the specs be considered bad and get revised? I thought C and C++ were advertised as language that don't do a lot of hand-holding and requires programmers to know what they are doing, and many aspects of it such as memory management really reflects that. So why is there implicit integral type conversion? Why not require programmer to always explicitly convert like Rust does?
- nwellnhof 4y agoForcing the programmer to convert integer types explicitly doesn't really help much. It makes it obvious that a conversion is happening, but that's it. People will simply add the required explicit casts without thinking about possible truncation or sign changes. UBSan has a very useful -fsanitize=implicit-conversion flag which can detect when truncation or sign changes occur, but this stops working when you make the cast explicit. So in practice, implicit casts actually allow more errors to be detected, especially in connection with fuzzing. Languages like Go or Rust would really need two types of casts to detect unexpected truncation.