11 ms·
Integers in C quiz
- RedShift1 4y agoI only have cursory experience with C, mostly by programming some Arduino stuff, so I can only add this: good god this is a minefield.
- rwmj 4y agoI've been a professional C programmer for nearly 40 years and didn't do especially well (I got about 2/3rds right). In my view it doesn't really matter. Enable maximum warnings and fix everything the compiler warns about. I also use Coverity once in a while, and every test is run with and without valgrind. If you do that you'll be fine.
- adastra22 4y agoYeah, in practice these sort of gotchas ought to trigger warnings. And for a C/C++ developer, warnings should never be allowed to persist in a code base.
- RedShift1 4y agoI thought some deductive reasoning and thinking about how things work at the byte level would save me. Computer said no.
- nayuki 4y agoWhen you write C programs, you are coding on the C abstract machine as specified by the language standard. If your code triggers signed integer overflow, then the C abstract machine says that it's undefined behavior, and the compiler and runtime can make your code behave however it wishes. It doesn't matter that the underlying concrete machine (POSIX, x86 ISA, etc.) has wraparound signed overflow, because your code has to interact with both the abstract machine and the concrete machine at the same time. See: https://www.youtube.com/watch?v=ZAji7PkXaKY https://www.youtube.com/watch?v=ZAji7PkXaKY
- petergeoghegan 4y ago> When you write C programs, you are coding on the C abstract machine as specified by the language standard. Are you really, though? I would argue that it's a matter of perspective and/or semantics. The Linux kernel is built with -fwrapv and with -fno-strict-aliasing, and uses idioms that depend on it directly. We can surmise from that that the kernel must be: 1. Exhibiting undefined behavior (according to a literal interpretation of the standard) OR: 2. Not written in C. Either way, it's quite reasonable to wonder just how much practical applicability your statement really has in any given situation -- since you didn't have any caveats. It's not as if the kernel is some esoteric, obscure case; it's arguably the single most important C codebase in the world. Plus there are plenty of other big C codebases that take the same approach besides Linux. Lots of compiler people seem to take the same hard line on the issue -- "the C abstract machine" and whatnot. It always surprises me, because it seems to presuppose that the only thing that matters is what the ISO standard says. The actual experience of people working on large C codebases doesn't seem to even get acknowledged. Nor does the fact that the committee and the people that work on compilers have significant overlap. I'm not claiming that "low-level C hackers are right and the compiler people are wrong". I'm merely pointing out that there is a vast cultural chasm that just doesn't seem to be acknowledged.
- nayuki 4y ago> In my view it doesn't really matter. One of these days, the compiler will do something surprising to one of your expressions involving signed integer overflow, like converting x < x + 1 to true. Or it'll delete a whole loop because it noticed that your code is guaranteed to trigger an out-of-bounds array read, e.g.: https://devblogs.microsoft.com/oldnewthing/?p=633 https://devblogs.microsoft.com/oldnewthing/?p=633 > If you do that you'll be fine. I would not trust code written based on the methodology you described. However, if you also add -fsanitize=undefined,address (UBSan and ASan) and pass those tests, then I would trust your code.
- rwmj 4y agoYes we do use the sanitization options too.
- bluetomcat 4y agoAlmost all of these examples would be sloppy programming in real code. The “int”, “short”, “long”, “long long” and “char” types are generic labels which shouldn’t be used where size and signedness matters. For a guarantee of size and signedness one should use the “[u]intXX_t” types. For sizes and pointer arithmetic - size_t. For subtracting pointers - ptrdiff_t. You simply wouldn’t have most of these issues if you stick to the correct types.
- rwmj 4y agoAbsolutely. int is a "code smell" for us, except in some well-defined cases (storing file descriptors for example). If someone is using int to iterate a loop, then the code is more usually wrong than right, they should be using size_t.
- fizzynut 4y agoI don't think a for loop using an int is bad or even "more wrong than right". If anything int is much better than using size_t. Using an integer, in the 1000s of for loops I've written, none get even remotely close to the billions - it is optimizing for a 1 in a million case, and if I know something can run into the billions of iterations I'm going to pay more attention to anyway. I've seen 0 occurrences of bugs relating to this kind of overflow. Using a size_t, it is effectively an unsigned integer that risks underflowing which can easily cause bugs like infinite loops if decrementing or other bugs if doing any index arithmetic. I've seen many occurrences of these kind of bugs.
- rwmj 4y agoOn Linux/x86-64 int is 31 bits, so you've probably introduced "1000s" of security bugs where the attacker only needs the persistence to add 2 billion items to a network input, local file or similar, to generate a negative pointer of their choosing. Any such code submitted to one of our projects would be rejected or fixed to use the proper type.
- fizzynut 4y ago
- jart 4y agoAnother interesting thing about C integers that the quiz doesn't cover is that remainder is not modulus. For example, in Python: >>: 2 % -5 -3 But in C: 2 % -5 == 2 If you want to use modulus in C rather than Euclidean remainder, then you have to use a function like this, which does what Python does: long mod(long x, long y) { if (y == -1) return 0; return x - y * (x / y - (x % y && (x ^ y) < 0)); }
- qsort 4y agoMathematically speaking, the mod is usually taken to be positive. Any reasonable definition would involve taking the quotient of Z over the congruence relation, so I can see both -3 and 2 being reasonable conventions to represent partitions. OTOH, the largest "wat" of C-like languages is the following: > -8 % 5 -3 why Python here is once again correct: >>> -8 % 5 2
- veltas 4y agoMathematically speaking if you ask for the modulus of -5 you may as well get a negative number, and I think people may validly have their own interpretations of what's "correct" at this point.
- qsort 4y agoI didn't say it's wrong. You may as well use {white, blue, black, red, green} to represent congruences mod 5, mathematically speaking it's not wrong, as long as they respect the axioms of a field. What's "wat" (in the same sense as the js "wat" talk) is that the answer changes if the argument becomes negative. By all reasonable definitions of modular arithmetic, -8 and 7 are in the same class mod 5. Why is then: > (-8 % 5) == (7 % 5) false in C-like languages? I'm pretty sure it's perfectly consistent with all the relevant language standards, but it's a "wat" nonetheless.
- masklinn 4y ago> What's "wat" (in the same sense as the js "wat" talk) is that the answer changes if the argument becomes negative. It's the same in Python though? you just prefer the way it behaves (though to be fair it's generally more useful and less troublesome): Python's remainder follows the sign of the divisor (because it uses floored division), while C's follows the sign of the dividend (because it uses truncated division). Strictly speaking, neither is an euclidian modulo.
- temac 4y agoUndefined behavior is probably the worst way we can imagine to define constraints usable by optimizers. Sad that major languages and implementations went this way.
- Karellen 4y agoYeah, I think a lot of C's `undefined behaviour` semantics around assignments to ints should be reconsidered and changed to `unspecified` or `implementation defined` behaviour, and compilers can just do "whatever the hardware does". If that includes traps on one arch, fine, let it trap. I think `undefined behaviour` still has its place in C - dereferencing a freed pointer comes to mind as an obvious example - but I think a good proportion of the really unintuitive UB conditions could be made saner without sacrificing portability or optimisation opportunities.
- owl57 4y agoIf you extend "unspecified" to allow traps, reading a bogus pointer can also be unspecified, only writes undefined in the current sense.
- Karellen 4y agoI don't think so. With "unspecified" and "implementation-defiend" behaviours, the implementation has to pick a behaviour and be consistent with it. The difference is whether they have to document that behaviour or not. If the hardware traps on bogus pointers, then reading a bogus pointer may trap. But if you read a recently-freed pointer, it may still be valid according to the hardware (e.g. will have valid PTEs into the processes address space) so won't trap. Therefore you won't be able to guarantee any particular behaviour on an invalid read, so I don't think you'd be able to get away with "unspecified" or "implementation defined" behaviour on most hardware.
- owl57 4y agoAFAIR reading uninitialized int, for example, is "unspecified" (any value could be there). If we consider adding "implementation defined with possible trap" for overflow, we might as well add "unspecified with possible trap" for reading an invalid pointer (any value could be there, or it could trap, but no nasal demons).
- gary_0 4y agoI got most of them right. My god, what have I become?
- deleted 4y ago[deleted]
- BirAdam 4y agoI have used C quite a bit, and I’m amazed at how many I got wrong. Nice example of why C is hated by so many I suppose. Personally, I love C but I don’t use it in anything serious. Probably for the best given I apparently cannot remember how C ints work.
- deleted 4y ago[deleted]
- jherskovic 4y agoHaven't written C in a long time. What a nightmare this is. Got most of them predictably wrong.
- codeflo 4y agoI thought I did well until the bit-shifting questions. Who in their right mind designs a language where shifting the bits of a u16 silently converts into an i32? Doubly so since that fact alone directly causes UB — keeping the u16 would have been perfectly fine. (Edit, since some respondents seem to miss this, explanations about efficiency or ISAs might justify promoting to u32 (though even that's debatable), but not i32. A design that auto-promotes an unsigned type, where every operation is nicely defined and total, into a signed type, where you run into all kinds of undefined behavior on overflow, is simply crazy.)
- veltas 4y agoBecause everything smaller than an int is usually promoted to int. int is the 'word' in C that things are calculated in. Even character constants are ints, all enum constants are ints, the default type was int when default types were still a thing.
- jefftk 4y agoBut why not turn u16 into u32? Why switch it to being signed on promotion?
- rwmj 4y agoI'm sure the answer is going to be along the lines of "because PCC did that and they standardized it" :-/ Here's a fun standardization problem I came across recently (nothing to do with C): http://mywiki.wooledge.org/BashFAQ/105 http://mywiki.wooledge.org/BashFAQ/105
- veltas 4y agoBelieve it or not, this makes the behavior more like what you'd expect in many cases. For example: uint8_t x = 4; extern volatile uint64_t *reg; *reg &= ~x; In the last statement x is promoted to an int, and then when the logical NOT occurs every bit is set to 1, including the high bit. When it's converted to a uint64_t for the AND, the high bits are also set to 1. So the result is that the final statement clears only bit 2 in *reg. If it promoted to unsigned int, then it would also clear bits 32-63.
- veltas 4y agoThird question is wrong. It's implementation defined, because unsigned short might be the same rank as unsigned int in some implementations, in which case it remains unsigned when promotion occurs.
- rwmj 4y agoHe does say on the first page: All other things being equal, assume GCC/LLVM x86/x64 implementation-defined behaviors. Are there any normal, modern machines where short and int are the same size? I think the last machine where that was true was the 8086.
- veltas 4y agoOn x86 systems like 8086 short and int were the same size. And that appears to be a footnote they've added after being called out for being wrong. The question gives "implementation defined" as an option and in other questions seems to specify the ABI, and in some assumes it without saying again. Very inconsistent, they should fix their quiz really. The last x86 processor I know of to have these sizes is 80286.
- galangalalgol 4y agoAvr microcontrollers still have 16bit ints, probably 8051 and pic too, but I don't use those. Lots of people do though. TI dsp uses 48 bit long, so don't count on int and long being the same either.
- moefh 4y agoThat's still a bad question: the behavior is implementation-defined according to the standard, so having "implementation-defined" as a wrong option is ambiguous and confusing. The question would be fine (given that note) if "impementation-defined" was not an option, like for example the question about "SCHAR_MAX == CHAR_MAX".
- fuckstick 4y ago> I think the last machine where that was true was the 8086. The last machine with a word size of 16 bits? The 286 was as well. There were others like the WDC 65816 (the Apple IIgs and SNES CPU). It just so happens that there simply far fewer 16 bit CPUs then there were 8 or 32 (or “32/16” like the 68k). Also 8 bit CPUs are simply a poor fit for C by their nature and the assumptions C makes. But the numerous ones still relevant today will use 16 bit ints. The use of Real or V86 mode on the x86 went on for many years after the demise of the 8086. I think it is a somewhat of a joke at this point that they’re teaching Turbo C in some developing countries.
- 6a74 4y agoNeat quiz. Reminds me that the absolute value of INT_MIN in C (and many other languages) is undefined, but will generally still return a negative value. This is a "gotcha" that a lot of people are unaware of. > abs(-2147483648) = -2147483648
- lizardactivist 4y agoA consequence of most, if not all, CPUs today using two's complement integers. I think one's complement is more sensible since it doesn't have this problem, but it loses out because it requires a more complex ISA and implementation.
- veltas 4y agoIt's annoying that negation, ABS, and division can overflow with two's complement. But how I look at it: lots of operations can already overflow, just a fact of signed integers, and you need to guard against that overflow in portable code already. It doesn't seem to be fundamentally worse that those extra operations can overflow.
- deleted 4y ago[deleted]
- nayuki 4y agoOnes' complement (correct spelling) has negative zero, which I would argue is a far worse problem.
- xigoi 4y agoWhy in the fuck is it “ones' complement”, but “two's complement”?
- tsimionescu 4y agoAccording to Wikipedia: > The name "ones' complement" (note this is possessive of the plural "ones", not of a singular "one") refers to the fact that such an inverted value, if added to the original, would always produce an 'all ones' number
- santimoller66 4y ago[flagged]
- dave84 4y agoDidn’t notice I got some wrong because the green color made me think I got them right.
- jbverschoor 4y agoThat’s to keep the obscurity vibe
- gonzo41 4y agoJust like programming in C. You think you got it right, but then bugs...
- pjmlp 4y agoOr thinking "how my compiler does it" == ISO C.
- ape4 4y agoYeah that's a UX bug in the quiz
- Nokinside 4y agoThe first rule of C good programming "Treat warnings as errors". Compile with all warnings enabled, selectively ignore only warnings you know for sure are not important for program semantics. Simple MISRA C with all warnings on is already close to language with strict type checking. C compilers give you a choice, use it. If you are programming for money, good static analyzer makes it possible to write safety critical code.
- veltas 4y agoI do agree about compiler warnings, but MISRA C imposes a lot of unnecessary rules, a lot of unhelpful rules on how you write expressions, and tries to also act like C's type system works a different way than it does. In practice I have found it to actually create bugs. Read the MISRA rules and appendices on their effective type model and the C standard, they have gaps where MISRA actually forces you to write code that looks correct and doesn't work with C's model. I strongly recommend against using MISRA, even in automotive or aviation code (although it may unfortunately be a requirement on any such project).
- pjmlp 4y agoWorth noting Dennis own words, "Although the first edition of K&R described most of the rules that brought C's type structure to its present form, many programs written in the older, more relaxed style persisted, and so did compilers that tolerated it. To encourage people to pay more attention to the official language rules, to detect legal but suspicious constructions, and to help find interface mismatches undetectable with simple mechanisms for separate compilation, Steve Johnson adapted his pcc compiler to produce lint [Johnson 79b], which scanned a set of files and remarked on dubious constructions." Dennis M. Ritchie -- https://www.bell-labs.com/usr/dmr/www/chist.html https://www.bell-labs.com/usr/dmr/www/chist.html Unfortunately too many think they know better than the language authors themselves.
- protomikron 4y agoWhat is the history of "undefined behavior" [in C compilers and the standard] in general? I suppose originally it was supposed to guide compiler engineers, but we all know that backfired, as many compilers try to exploit undefined behavior to optimize code, but that can be problematic in security sensitive code (e.g. if uninitialized memory is optimized away) - there have been discussions between security engineers, kernel developers and GCC hackers about how to implement/interpret the standard. Would it be possible to have a standard, where undefined behavior is just a compile error? What would we lose - apart from legacy compatibility?
- lizardactivist 4y agoI really hate C.
- qznc 4y agoI made a similar test for floating point: https://beza1e1.tuxen.de/no_real_numbers.html https://beza1e1.tuxen.de/no_real_numbers.html Since most languages use the same IEEE-754, you can hate them all.
- lizardactivist 4y agoUnbiased, equal hate, fully in line with today's political correctness? Fine, I really hate programming languages.
- Turing_Machine 4y agoThe correct answer for many of these is "don't do that". :-)
- IncRnd 4y agoThat is the correct answer to the questions in this quiz! Most professionals don't worry about these effects, instead choosing to cast and use parenthesis directly. Those instruct the compiler instead of relying upon warnings from the compiler.
- Cu3PO42 4y agoOne thing to note is that long int is the same size as int on x64 Windows, at least in the MSVC ABI. clang also conforms to this. This is relevant to the question asking if -1L > 1U.
- auxym 4y agosame with ARM-EABI (32bit cortex-M MCUs). Int and long int are both 32 bits.
- MobiusHorizons 4y agoI think that is expected (it’s what happens for x86 as well) what’s surprising about the parent is that long is apparently 32 bit on windows x64. Usually long should be 64 bit on a machine with 64 bit words
- antirez 4y agoSurprised I got all the questions right because I tend to code around those limits, sticking to defining always safe types for the problem at hand, in all the cases I'm not sure about ranges, possibile overflows and so forth. What I mean is that if you have to remember the rules in a piece of code you are writing, it is better to rewrite the code with new types that are obviously safe.
- bornfreddy 4y agoAdmittedly my C is (very) rusty, but I was surprised at how few of the answers I knew, so your comment made me feel even worse. But then I saw your nickname. Yeah. :) (redis rocks btw) Completely agree with you, and not just in C. Using esoteric features of any language is equivalent to putting landmines in front of your teammates - bad idea.
- tomxor 4y ago> Using esoteric features of any language is equivalent to putting landmines in front of your teammates Also, outside of production code, using esoteric features is a good way to get familiar with every corner of that language - which is useful so that you can diffuse those landmines when they are accidentally created. i.e know them to avoid them.
- leni536 4y agoDoesn't list my favorite footgun. x and y are unsigned short. The expression `x*y` has defined behavior for... a) all values of x and y. b) some values of x and y. c) no values of x and y.
- deleted 4y ago[deleted]
- shultays 4y agoI am gonna say A but I guess I dont the foot gun here
- Veliladon 4y agoThe shorts are not promoted to ints (if you even declared the result as that type) until after the multiplication. The result will first be put into a short and then promoted to int. It's basically asking for an overflow error. Given that 256^2 is 65536 you don't have to be multiplying large numbers before hitting that overflow.
- loeg 4y agoUnsigned short has defined overflow, though.
- shultays 4y agoI don't follow, assuming short is half the size of int it would only overflow if most significant bits of both values are 1. Where did that 256^2 come from? It wouldn't overflow if a and b were 256 I missed that the result would be promoted to signed int, which only most significant bits are set
- deleted 4y ago[deleted]
- LegionMammal978 4y agoAll operands are always promoted to int (or unsigned int, long, unsigned long, etc.) before any operation. The footgun in this example is that even though you're using unsigned integers and would expect guaranteed wrapping semantics, the promotion to signed int makes it UB for USHORT_MAX*USHORT_MAX.
- analog31 4y agoOne of my friends likes to scold me about using a programming language (Python) that doesn't enforce type declarations. I gently remind him that his language (C) has eight different types of integers.
- einpoklum 4y ago{ char, short, int, long, long long } x { signed, unsigned } = 10 types, and then there's bool and maybe int128_t, so maybe 12.
- analog31 4y agoAha, I had forgotten about char.
- Aardwolf 4y agoHeh, it has way more than 8. For char, you have 3: signed char, unsigned char and char. It's not specified if char without keyword is signed or unsigned. You have integer types such as size_t, ssize_t and ptrdiff_t. They may, under the hood, match one of the other standard int types, however this differs per platform, so you can't e.g. just easily print size_t using the standard printf formatters, you really have to treat is as its own type. Also wchar_t and such of course. Then you have all the integers in stdint.h and inttypes.h. Same here applies as for size_t. At least you know how many bits you get from several of them, unlike from something like "long". Then your compiler may also provide additional types such as __int128 and __uint128_t.
- spc476 4y ago> so you can't e.g. just easily print size_t using the standard printf formatters This has been fixed in C99. For size_t, it's "%zu", for ptrdiff_t it's "%td", for ssize_t it's "&zd" and for wchar_t, it's "&lc".
- sposeray 4y ago[dead]
- einpoklum 4y agoI taught first-semester C for several years, and still got a couple of these wrong - although, to be honest, the way we taught the class at my alma mater we steered well clear of these situations. We told students that C perform type promotions and automatic conversions, but either had them use a uniform type to begin with - int typically - or told them to convert explicitly and avoid Still, the most important suggestion I would make here is: Always compile with warnings enabled, in particular: * -Wstrict-overflow=1 and maybe even -Wstrict-overflow=3 * -Wsign-compare * -Wsign-conversion * -Wfloat-conversion * -Wconversion * -Wshift-negative-value (or just `-Wall -Wextra`) And maybe also: * -fsanitize=signed-integer-overflow * -fsanitize=float-cast-overflow (These are GCC flags, should work for clang as well.)
- dinom 4y agoSeems like a good example of why interview quizzes aren't a panacea.
- MauranKilom 4y ago> What does the expression SCHAR_MAX == CHAR_MAX evaluate to? > Sorry about that -- I didn't give you enough information to answer this one. The signedness of the char type is implementation-defined ...why not have an "implementation-defined" answer button then, because that's what people should know (instead of knowing all ABIs) and what the question is about anyway? > If these operators were right-associative, the expression [x - 1 + 1] would be defined for all values of x. That's just wrong, no? If + and - were right-associative, it would be parsed as x - (1 + 1), which is decidedly not "defined for all values of x".
- shultays 4y agoI raised an eyebrow on that as well, in some questions you have implentation defined for an answer so I assumed the author just wrongly assumed undefined covers that
- necovek 4y agoOther questions might also be "implementation defined", thus a caveat to assume GCC/LLVM implementations on x86/amd64 at the start. I.e. C standard enforces undefined very sparingly iirc, and most of the corner cases are implementation defined. I may also be misremembering things: it's been 20 years since I've carefully read C99 (draft, really) for fun :))
- kevin_thibedeau 4y agoEven the compiler assumption isn't enough. There is also an implicit assumption in the answers that x86-64 is using LP64 when some platforms will use LLP64 (Windows) or ILP64 (Cray).
- Lockal 4y agoThe answer for question about SCHAR_MAX == CHAR_MAX is just wrong there. Of course it is "undefined", or actually, it is configurable with "-funsigned-char" flag (for GCC/Clang/ICC). https://godbolt.org/z/PTEoW91v5 https://godbolt.org/z/PTEoW91v5
- manaskarekar 4y agoTangentially related, https://cppquiz.org/ https://cppquiz.org/, for C++.
- simias 4y agoI did fairly well in the test (I didn't remember that you couldn't shift into the sign bit), but it really helps highlight how stupid the C promotion rules are. In C as soon as I have to do arithmetics with anything but unsigned ints all sorts of alarm bells start going off and I end up casting and recasting everything to make sure it does what I think it does, coupled with heavy testing. Now add floats and doubles into the mix and all bets are off. Rust not having a default "int" type and forcing you to explicitly cast everything is such an improvement. Truly a poster child for "less is more". Yeah it makes the code more verbose, but at least I don't have to worry about "lmao you have a signed int overflow in there you absolute nincompoop, this is going to break with -O3 when GCC 16 releases 8 years from now, but only on ARM32 when compiled in Thumb mode!"
- tialaramex 4y agoStill, I would rather not have Rust's 'as' cast. I should like to see all, or at least most uses of 'as' deprecated in a later Rust edition. Rust's 'as' will silently throw away data to achieve what you asked. Sometimes you wanted that, sometimes you didn't realise, and requiring into() and try_into() instead helps fix that. For example suppose I have a variable named beans, I forgot what type it is, but it's got the count of beans in it, there should definitely be a non-negative value because we were counting beans, and it shouldn't be more than a few thousand, so we're going to put that in a u16 variable named enough. let enough = beans as u16; This works just fine, even though beans is i64 (ie a signed 64-bit integer). Until one day beans is -1 due to an arithmetic error elsewhere, and now enough is 65535, which is pretty surprising. It's not undefined but it is surprising. If we instead write let enough = beans.into(); we get a compiler error, the compiler can't see any way to turn i64 into u16 without risk of loss, so this won't work. We can write beans.try_into().unwrap() and get a panic if actually beans was out of range, or we can actually write the try_into() handler properly if we realise, seeing it can fail, what we're actually dealing with here.
- bestouff 4y agoI feel you. I'd really like a way for "as" to be transformed into "try_into().unwrap()", say in a later edition. Or even just "into()" which would throw a nice compile-time error - This is the Rust Way.
- svnpenn 4y agoExactly why I don't use C anymore. Other languages like Go don't allow this stuff. https://go.dev/play/p/D2J6Y9ol41W https://go.dev/play/p/D2J6Y9ol41W
- loeg 4y agoThe quiz is a little broken. CHAR_MAX is implementation defined but for some reason that question doesn’t have that option, even though other questions do.
- flykespice 4y agoThis quiz only reminded me how little I know about C (thankfully those case are corner-cases of incompetent programming so other and I can ignore their existence). Good grief, thanks Quiz for reminding me to stay away from that mess of language.
- nayuki 4y agoThis tool I recently made can help: https://www.nayuki.io/page/summary-of-c-cpp-integer-rules#arithmetic-conversion-rules-simulator https://www.nayuki.io/page/summary-of-c-cpp-integer-rules#ar... For example, you can see what (signed long) > (unsigned int) would convert to, under different environment bit width assumptions. Also, there's a discussion on Reddit: https://www.reddit.com/r/cpp/comments/x4x01f/cc_arithmetic_conversion_rules_simulator/ https://www.reddit.com/r/cpp/comments/x4x01f/cc_arithmetic_c...
- jstimpfle 4y agoIt's important to notice the disclaimer that this is applies to x86/x86-64 GCC like platforms, in particular int is assumed to be 32 bits. As antirez said as well, I don't pride myself in understanding the intricacies of integer arithmetic and promotion well. I try to write clear code by writing around the less commonly understood rules. Nevertheless I wanted to test myself. There are two questions that surprised me somewhat. Apparently you can't left-shift a negative value even by a zero amount, as in (-1 << 0). And is it true that the value of "-1L > 1U" is platform dependent? I had assumed that 1U would be promoted to 1L in this expression, even on x86 where unsigned int and long have the same number of bits. According to the following document, long int has a "higher rank" than unsigned int. https://wiki.sei.cmu.edu/confluence/display/c/INT02-C.+Understand+integer+conversion+rules https://wiki.sei.cmu.edu/confluence/display/c/INT02-C.+Under... . (Edit: according to rules 4 and 5 of "Usual arithmetic conversions", it's not only the rank but also about "the values that can be represented")
- greesil 4y ago-Wall -Werror #include <stdint.h> and don't use primitive types, and you will avoid many of these issues.
- jcranmer 4y agoThe answer of the final question (INT_MIN % -1) is wrong in a way that's somewhat dangerous. If you read the text of C99 carefully, yes, it's implied that INT_MIN % -1 should be well-defined to be 0. However, the % operator is usually implemented in hardware as part of the same instruction that does division, which means that on hardware where INT_MIN / -1 traps (thereby causing undefined behavior), INT_MIN % -1 will also trap. The wording was changed in C11 (and C++11) to make INT_MIN % -1 explicitly undefined behavior, and given the reasoning for why the wording was changed, users should expect that it retains its undefined behavior even in C89 and C99 modes, even on 20-year-old compilers that predate C11.
- greaterthan3 4y ago>The wording was changed in C11 And here's an exact quote from the C11 standard: >If the quotient a/b is representable, the expression (a/b)*b + a%b shall equal a; otherwise, the behavior of both a/b and a%b is undefined. http://port70.net/~nsz/c/c11/n1570.html#6.5.5p6 http://port70.net/~nsz/c/c11/n1570.html#6.5.5p6
- lultimouomo 4y agoBeware that this is very much not a "C Integer quiz", but a "ILP32/LP64 Iinteger quiz". As sono as you move not to some weird exotic architecture, but simply to 64bit Windows(!!) some quiz answers will not hold. For a website meant to educate programmers on C language gotchas, this is a pretty lackluster effort. Even the initial disclaimer, "assume x86/x86-64 GCC/CLang", is wrong, as the compiler does not have anything to do with integer widths.
- deleted 4y ago[deleted]
- flykespice 4y agoMy impression is this wasn't muxh to educate programmers on C language gotchas but to remind you just how messy and fragile this language is (so you can stay far away).
- lultimouomo 4y agoOne more reason not to give the impression that you can assume that long is wider than int which is wider then short!
- ok123456 4y agoThe quiz is wrong because they assume that the length of short is less than int in some questions. A short can be the same length as an int. It just can't be longer.
- ninefathom 4y agoI noticed this when I got to some of the x86 vs. x86-64 questions. Occasionally I'll tutor C and C++ to college students, and I swear that I spend half of my time in such cases correcting erroneous (or absurdly incomplete) info provided by instructors, Stack Exchange articles, etc. It's especially challenging when I get, "but I read it on HN?!"
- up2isomorphism 4y agoThese examples do look scary. However, in my 16 years of experience of mostly writing In C, I have never found a single chance that I need to actually use the expressions that I got the answers wrong. Never mix unsigned and signed integer comparison unless you know exactly what you are doing. And never do arithmetic on boundaries definitions like INT_MAX, they are boundaries , why you need to compute a derived value on boundaries? If you do not need arithmetic behavior, do not use signed integer, use unsigned. Because computer does not understand sign, so if you do not need a sign, do not use it. You do not need to be a language committee member to write C , you just need to understand the reason behind its design.
- int_19h 4y agoIt's not always obvious that you're mixing signed and unsigned, though. I think the biggest source of these kinds of bugs is because size_t is unsigned but ptrdiff_t is signed. So the moment you mix pointer subtraction with sizeof, footguns abound.
- jcelerier 4y agoThe problem is that for unsigned one of the boundaries is 0, which is an extremely common number - there isn't a couple months where I don't find a bug due to a size-1 somewhere
- 10000truths 4y agoSubtraction would presumably fall under the arithmetic behavior that OP was talking about.
- eru 4y agoMaybe. But subtraction is also perfectly well defined for unsigned ints in C.
- kcexn 4y agoIf you wanted to be extremely careful, you might pass unsigned ints into a function by copy, and cast it as a signed int to perform arithmetic, then do a boundary check before returning a result to be assigned back to an unsigned integer. The unsignedness of the integer lets readers of the code know that it's a constant of some kind, and that comparisons should be performed with care. Normally, when I've worked with C (fairly limited), unsigned numbers normally get used as flags for bitwise comparisons. Sometimes your flags may have a partial ordering defined on them (so a sense of flag A being 'smaller' than flag B), so you might need some arithmetic to do those checks you need to be explicitly careful with the boundary checks though.
- ynfnehf 4y agoAnother fun one: struct { long unsigned a : 31; } t = { 1 }; What is t.a > -1? What about if a is instead a bit-field of width 32? (Assuming the same platform as in the quiz.)
- junon 4y agoJust a note for the author: The Green background on wrong answers was entirely confusing. Thought I was a C god at first.
- synergy20 4y agotypically you shall avoid shift on signed integers, especially NEVER left shift on signed char|short|int|whatever. I limit shift strictly to unsigned integer numbers.
- nayuki 4y agoFollowing this rule strictly can be tricky. uint16_t x = (...); uint16_t y = x << 15; Any arithmetic involving uint16_t will be promoted to some kind of int. If int is 16 bits wide, then uint16_t will be promoted to unsigned int before the shift, and all values of x are safe. Otherwise int is at least 17 bits wide, then uint16_t will be promoted to signed int before the shift. On a weird but legal platform where int is 24 bits wide, the expression (uint16_t)0xFFFF << 15 will cause undefined behavior. My workaround for this is to force promotion to unsigned int: (0U + x) << 15. https://stackoverflow.com/questions/39964651/is-masking-before-unsigned-left-shift-in-c-c-too-paranoid/39969562#39969562 https://stackoverflow.com/questions/39964651/is-masking-befo...
- kazinator 4y agoFound a disappointing bug in the test: (unsigned short)1 > -1 Correct answer is: implementation-defined. The left operand of > has type unsigned short, before promotion. On C implementations for today's popular, mainstream machines, short is narrower than int; therefore, whether it is signed or unsigned it goes to int. In that common case, we are doing a 1 > -1 comparison in the int type. However, unsigned short may be exactly as wide as int, in which case it cannot promote to int, because its values do not fit into that type. It promotes to unsigned int in that case. Both sides will go to unsigned int{*}, and so we are comparing 1 > UINT_MAX which is 0. Maybe the author should name this "GCC integer quiz for 32 bit x86", and drop the harder choices like "implementation-defined". --- {*} It's more nuanced here. If we have a signed and unsigned integer operand of the same rank, it could go either way. If the unsigned type has a limited range so that all its vallues are representable in the signed type, then the unsigned type goes to signed. My remark represents only the predominant situation whereby signed and unsigned types of the same rank have overlapping ranges that don't fit into each other: the unsigned version of a type not only lacks negatives, but has extra positives.
- jwilk 4y agoDiscussed in this thread: https://news.ycombinator.com/item?id=32712578 https://news.ycombinator.com/item?id=32712578
- mort96 4y agoThe site says: > All other things being equal, assume GCC/LLVM x86/x64 implementation-defined behaviors.
- RicardoLuis0 4y agothat's still wrong, the integer data model is defined by the target, which is not specified in the quiz, not solely by the compiler, ex. clang uses 32-bit longs when compiling for windows, and 64-bit longs when compiling for linux: * windows - https://godbolt.org/z/WWWzarEsK https://godbolt.org/z/WWWzarEsK * linux - https://godbolt.org/z/57WK45o6e https://godbolt.org/z/57WK45o6e same for gcc on linux/windows (mingw)
- ummonk 4y agoWait so does an unsigned int promote to signed int for shift?
- Dwedit 4y agoOn Windows, `long` and `int` are the same size, even when building for x64.
- ghoward 4y agoI'm a heavy use of C, and most of what I got wrong were around integer promotion. I'm glad I run clang with -Weverything and use ASan and UBSan.
- boxfire 4y agoIt's very worth pointing out and in fact advocating for the compiler options -fwrapv and -ftrapv Which both make signed integers take the expected two's complement behavior, or traps signed integer overflow, respectively. N.B. left shifting into the sign bit is still undefined behavior... On x86-64 gcc and clang seem to perform the shift as if the number is interpreted unsigned, then shifted, then interpreted signed.
- ananonymoususer 4y agoI have an issue with this one: Assume x has type int . Is the expression x<<32 ... Defined for all values of x Defines for some values of x Defined for no values of x (chose second answer) Wrong answer Shifting (in either direction) by an amount equalling or exceeding the bitwidth of the promoted operand is an error in C99. So according to Wikipedia: https://en.wikipedia.org/wiki/C_data_types https://en.wikipedia.org/wiki/C_data_types int signed signed int Basic signed integer type. Capable of containing at least the [−32,767, +32,767] range.[3][a] So a minimum of 16 bits is used for int, but no maximum is specified. Thus, if my C compiler on my 64-bit architecture uses 64 bits for int, this is perfectly allowed by the specification and my answer is correct.
- nayuki 4y agoThe top of the page says: > All other things being equal, assume GCC/LLVM x86/x64 implementation-defined behaviors. However, you're right to point out that the quiz would be better if you can't make any more assumptions than guaranteed by the basic language standard.
- deleted 4y ago[deleted]
- Jimajesty 4y agoI felt pretty smart getting that first question, then proceeded to fall down the stairs.
- CamperBob2 4y agoCorrect answer to most of these questions: "I don't know, and I don't care, because it would never even cross my mind to write code in which most of these questions would come up. If forced to review or debug code written by someone else who knew the answers and leveraged that knowledge, I would either complain about it loudly or rewrite it quietly." C, like Rome, is a wilderness of tigers. Why ask for trouble?
- phist_mcgee 4y agoI know this is a tangential comment, but the fact that the site author went to the effort to add a css reset, and then doesn't go ahead and add in any kind of margins is pretty bizarre. The fact that the text butts up to the left of the page with no margin is pretty incredible.
- siggen 4y agoGot all these correct. I was expecting something more convoluted or exotic undefined behavior.
- Cola2265 4y ago
- forrestthewoods 4y agoIn my opinion the three original sins of C are: nullptr, null-terminated strings, and implicit conversions. Abolish those three concepts and C is a significantly improved language!
- pjmlp 4y agono bounds checkings, enums are hardly better than #define, pointer decay....
- jstimpfle 4y ago> pointer decay This is an issue? Works fine for me.
- pjmlp 4y agoIt does wonders for security researchers jobs, because the idea of typing &arr[0] instead was asking too much.
- jstimpfle 4y agoWhy _can_ you write &arr[0] in the first place? There is at least some logic behind it (which probably breaks down with multidimensional arrays, a feature that probably wasn't there from the start). In C, I suspect that at least in the beginning, there were never arrays on the type and expression level - only pointers. What security problems are exactly caused by pointer decay? A similar thing also exists with calls through function pointers, and I do not think you can find many programmers who are willing to write (*foo)(x, y, z) when using function pointers (at least not when there are many, like when using e.g. OpenGL). Or worse, (&foo)(x, y, z) with normal functions.
- pjmlp 4y agoThe usual stuff that array lengths on function declarations are only guidelines, given that they are plain pointers, and when one calculates the array length not taking that into account, somewhere out there there is an happy hacker.
- pif 4y agoIn the end, it's very simple and intuitive. 1- If you need arithmetic, use signed; if you need a bitmask, use signed. C is not assembly, and bit shift is no multiplication nor division. 2- Make sure you stay within bound, as in: don't even think you can approach the boundaries. C is not assembly, and overflow flag does not exist.
- deleted 4y ago[deleted]
- xyzzy_plugh 4y agoIt's a bit frustrating that/I don't know why "implementation defined" and "assume x86" are both present. For most of these there is a fairly specific x86 implementation detail. For example, short char vs char size.
- malkia 4y agoAt this point, I'm Jon Snow. I'll just... anyway...
- attah_ 4y agoIt would have been good if the feedback wasn't green (and for bonus points; not the same) for wrong answers.
- knorker 4y agoWatch out: The box becomes green no matter if you get it right or wrong.