An intro to Zig's integer casting for C programmers
lagerdata.com
lagerdata.com
You already know someone will teach their students to always have it off because its "slower" or something.
Make something idiot-proof and the world invents a better idiot.
Another language that does safety like this incredibly well is Ada (Ada/SPARK), and I'm unsure why people aren't more hyped about it. So many people hype Rust or Zig or whatever new language, and yet there's an incredibly safe and expressive language that's used in high-reliability applications like missile guidance systems, that nobody seems to talk about.
Safety (of all kinds) is not the only selling point of Rust and Zig, and the fact that Ada also have safety measures doesn't mean that it's instantly an option for me.
For example, I keep seeing people hype about Zig/Rust, for all kinds of reasons; and the way that they present their arguments is very compelling. While I've heard of Ada before, AFAICT the only context in which it is brought up is to downplay hype over Rust/Zig; never as a standalone.
Sounds like a PR problem, mostly.
EDIT: Not to say that there aren't other problems, just saying that this point alone isn't some magic bullet.
I don't like Rust because it gives me memory safety, tons of languages do that. I love Rust because the tradeoffs it gives me worth the switch, and the overall tooling and ecosystem are very well made.
It's the case that the Zig creator did put a high priority on soft "PR" for the language, the first hire was a developer advocate/community manager. I think this is a great case of "lessons learned" from the history of programming languages.
Same applies to the tooling of Ada/SPARK, but as you have said, it is pretty much a PR issue.
OCaml has seen the alternative "Reason" syntax (JS-like) grow in popularity. Maybe a C-like (or better, rust-like) syntax for Ada would help the language's adoption. People already using Ada would complain that the current syntax is fine but they're not the target demographic :-)
I can easily read and understand someone's Ada, C, or OCaml code and actually know what is going on, but I cannot read and understand even my own Perl code (after a week or two), or other people's Rust code. I would rather prefer reference implementations to be in C than in Rust, too. If I read the C version, I can easily port it to any language vs. if it were in Rust.
OCaml does not look like Rust to me (OCaml seems more consistent, and Rust seems like a mixed bag of everything to me). It does not hide as much behind symbols for example as Rust does, I think, and learning it was really easy. I tried to read Rust, I really did, but everything is so hidden from me. I did not mean to say that any of the mentioned languages are anywhere close to C though. In any case, if I had to look at reference implementations, C would be the best (to me). It is really easy to know what is going on and why, and thus it is easy to implement it in any languages I know. Probably because it is not a language with many high-level abstractions or language constructs (syntactic sugars) that hide what is going on.
Example snippets as to why I dislike Rust:
let mut parents_array = ArrayVec::<[&[u8; BLOCK_LEN]; MAX_SIMD_DEGREE_OR_2]>::new()
let input_ptrs: &[*const u8; DEGREE] = &*(inputs.as_ptr() as *const [*const u8; DEGREE]);
And this is nothing, there are much worse ones, and I would have to give you files for that, but pretty much any famous Rust project is difficult to read for me. I really do not understand most Rust code, I wonder if the problem is with me.I still dont understand this, you spend 80% of the time thinking about code, 19% reading, and 1% typing.
I don't even remember much, just that how much I loved just the look of the example programs, but that was during community college when I was new to programming. It wasn't part of a class, but the guy who implemented the curriculum just jammed the library with jewels and the entire library collection was just full of classics especially since the actual curriculum was just a basic associates in "business data processing."
For example, a couple of features come together really nicely to make memory safety easier to test in Zig: * You need a reference to an Allocator to be able to allocate memory, so as a general rule, the caller can control which allocator is used. * Unit testing is integrated well into the language. * Therefore, you can create an allocator for each unit test, and fail the test at the end if any memory was leaked. * This process can also happen at the application level with the General Purpose Allocator, which can let you print an error when the program exits if anything was leaked.
The above doesn't solve every memory safety problem (and there are other features like native bounds-checked slices that solve other kinds of issues), but it provides an extra layer that can probably get us quite far into the "quite safe" camp.
https://devblogs.microsoft.com/cppblog/new-static-analysis-r...
https://devblogs.microsoft.com/cppblog/finding-bugs-with-add...
https://docs.microsoft.com/en-us/cpp/code-quality/using-sal-...
https://docs.microsoft.com/en-us/visualstudio/debugger/how-t...
No need to switch languages with a lesser eco-system, just learning to turn on the compiler switches that are already there.
There were no free beer compilers and no 8/16 bit home computer was capable of hosting an Ada compiler, Basic, Pascal and Modula-2 was the best they could manage.
Is there a good compiler that one can install for free?
Are there a few good and comprehensive books / references / guides, available online for free?
If you want something to become popular, give it away. Ideally, push it. At the very least, have a limited free version. Or turn a bling eye to small-time piracy, as many vendors did for a long time. Or make it dead easy to buy it for $10.
(None of the above works for you? Sorry, you have just turned down 99% of kids who might like to tinker with your tech, love it, and then promote it wherever they go. Your tech may be hot and desired in the narrow circle of pros, but it's not going to become popular and win the world.)
Accessibility is really not the problem. The problem is, Ada is an old language that has many similar problems to C: lack of a good package management story, and a design by committee making language evolution glacially slow (though that also doubles as a feature). It also lacks a vibrant ecosystem like we can find in other popular languages.
Furthermore, SPARK in particular takes the concept of safety much further than Rust or Zig do right now, as it allows proving the correctness of a program according to a formal specification. Rust/Zig only care about proving the absence of UB. This makes SPARK much more complex, and thus have a much higher barrier of entry.
The problem for older languages is that the bar for what's expected of a language has risen substantially. A long time ago, languages weren't even expected to have implementations. Today, not only are implementations expected for all major platforms, languages are also expected to run on phones and the browser, include package managers and library repositories, have a language server implementation and editing modes for all major IDEs, be open source with active development, provide extensive documentation on the scale of a book, and also promote a vibrant and active community. Oh, and to top it off, users don't want to pay for any of that. It's just expected, which is why most languages these days only come out of large tech companies that can afford to fund all of the above with no expectation of profit.
A better starting point might be http://www.GetAdaNow.com/
The most prominent project that i know of written in ada is ghdl.
Sure, but if you only ever give people safety scissors then you're severely limiting the kinds of things that they can build. You have to let people who know what they are doing be able to do what they need to do, so you have to be able to turn the runtime safety off. Zig can do this at the scope level.
If you dont want full control like in C++, a language would be nice that has one specific style, one specific way to do things, and so on. Go(lang) is quite close to this, in my experience. You can't do thread safety wrong, because there's only really one way, and so on.
I would love a language with
1. Explicit nullable types (not like Java's "anything can be null" design), so everything is a non-nullable reference type unless its "optional<T>" for example. I strongly support the idea of a nullable type only being used where it being null carries information.
2. Strong typing - like, tungsten strong. Implicit conversions need to be compiler errors, no implicit constructors, etc. with simple explicit casting
3. One style - and it better not be Java-like forced-OOP.
4. Full and clear memory control, RAII support, no gc. I need my RAM for other stuff.
I'm not sure if there's a language like that out there. I don't care for library support, I just want a fun language.
The new gc is pretty much compiler assisted scope managed smart pointers as well. Also when using the gc you can build your own types with custom create/free/copy/move operators to do what you want without worrying about a stop the world gc.
Using the arc gc pretty much compiles down to what you'd do manually. For cycles you can use the orc gc, again it's all opt in.
I find this a great balance of productivity and performance, where it's easy to have high control when you want it, and still get good performance when you're not bothered.
With the new ARC & move semantics, Nim has hit a sweet spot, IMHO. It's like the language struggled to find a fit for a long time. But ARC allows very low overhead memory safety, perfect for mcu's and wasm in particular.
Though perhaps Swift could be a contender in this arena as well with its ARC, but it's development is so Apple centric.
What's interesting to me is that with move semantics and smarter compiler analysis, an ARC based GC overhead approaches that of Rust's compile time lifetime memory management. For any non-trivial program Rust seems to use a lot of Rc's or copies to get around lifetime analysis issues. So if the compiler can automatically figure out lifetimes in code it can eliminate many ARC operations.
I hope more languages adopt more flexible ARC based gc's or improve on rusts ergonomics.
If you're really responsible, it's possible to use the system allocator to inform the system about how much memory your allocations consume so that the memory pressure triggers have a correct accounting of how much memory is being used.
Then on the past languages that failed to gain steam, Mesa/Cedar, Modula-2+, Modula-3, Oberon, Oberon-07, Oberon-2, Active Oberon, Eiffel, Sing#, System C#, Component Pascal, among many others.
The only thing missing is that many are badly taught, use new everywhere and don't bother to fully understand all language features.
It makes for a very performant pure functional language. My only gripe is that the stdlib is abysmal, and hardcoded into the compiler.
- value types
- stackalloc is safe since C# 7
- SafeHandles since C# 2.0
- IDispose interface
- IDispose like Dispose() since C# 8
- Marshal class since C# 1.0
- Span<>() classes since C# 7
- static lambdas since C# 9
- native function pointers since C# 9
You don't hear about the struggles of using it in practice because the projects you've pointed out are usually confidential.
In my experience MISRA is a much more popular standard for secure programming in the defence industry versus Ada. MISRA is a C standard, and yes, it runs missile systems, Boeing braking systems, you name it.
Ada suffered from its domain, original price of compilers, and the few UNIX vendors that cared to offer compiler like Sun, it was an additional acquisiation on top of UNIX SDK.
Everyone knows that only newbies do coding errors in C, so why spend the extra money? /s
The Sun C compiler was an additional cost item, just like everyone else.
That was my point.
https://www.nongnu.org/gm2/homepage.html
However I doubt the language gets much use nowadays beyond some legacy code bases, its opportunity is now gone.
The Ariane 5 maiden flight disaster illustrated quite clearly that the choice of language has little influence on the actual correctness of a program.
Ada on its own is no better than Pascal in that regard. A formally verified and thoroughly tested MISRA C program can be safer and more correct than a sloppily written Ada program.
So the question is indeed not as rhetorical as one might think - why spend the extra money indeed? Isn't it better spent on verification, testing, tooling and culture, which benefits the development regardless of programming language?
So yes, it is quite worthy to reduce the amount of money spent in verification, testing, tooling and culture.
The alternative is to just give up that programmers will never learn and just force verification at hardware level, like Google is doing on Android.
"Memory Tagging for the Kernel: Tag-Based KASAN"
https://www.youtube.com/watch?v=f-Rm7JFsJGI
Oracle on Solaris SPARC,
https://docs.oracle.com/cd/E37838_01/html/E61059/gqajs.html
Apple on iOS,
https://developer.apple.com/documentation/security/preparing...
Microsoft on Azure Sphere,
https://www.microsoft.com/security/blog/2020/11/17/meet-the-...
http://www-users.math.umn.edu/~arnold/disasters/ariane5rep.h...
http://www.adapower.com/index.php?Command=Class&ClassID=FAQ&...
I would love to see something like "Rustlings" for Ada, as I found that was a good way to practice not only writing code, but reading it as well.
I was able to self-teach Haskell and Erlang without any major problems, and even managed to ship applications written in it commercially.
(Looks like I found a use for the new Rosetta on my M1 Mac.... I wonder when there will be builds for aarch64 for Darwin)
:D
My argument is that if I need that insane speed and safety features have to be off I should actively work for that not the other way around that I should actively work for safety.
Why? Because we forget to do things.
> Another language that does safety like this incredibly well is Ada (Ada/SPARK)
I wanted to learn Ada for a long time. Do you have a guide or tutorial how to get into it?
Especially these ones: https://news.ycombinator.com/item?id=21435869 and https://news.ycombinator.com/item?id=21437498
Sorry if a lazy question, last time I looked at ada was decades ago and I'm surprised to find enthusiasts for it on HN.
edit: an advantage for c is that you can get loads of examples just googling, sucks for less used languages I guess.
- https://en.wikibooks.org/wiki/Ada_Programming/Libraries/GNAT... (search for "C select()")
- https://www.codelabs.ch/anet/
- https://github.com/samueltardieu/adasockets
- https://github.com/rtyler/ada-playground/blob/master/epollec...
Some old reading: https://brokenco.de/2013/04/07/async-with-ada.html
You may want to check how GNAT.Sockets and Anet are implemented, too. I know that GNAT code is heavily documented.
https://news.ycombinator.com/item?id=19122884 (!)
https://news.ycombinator.com/item?id=19245898 (!!)
https://news.ycombinator.com/item?id=19274244 (!!)
https://news.ycombinator.com/item?id=19274412
https://news.ycombinator.com/item?id=19770405
https://news.ycombinator.com/item?id=20776296
https://news.ycombinator.com/item?id=20934511 (!!) [3]
https://news.ycombinator.com/item?id=20939336 (!!)
https://news.ycombinator.com/item?id=21286061
https://news.ycombinator.com/item?id=21286292
> These runtime checks[1] are costly, both in terms of program size and execution time. It may be appropriate to remove them if we can statically ensure they aren't needed at runtime, in other words if we can prove that the condition tested for can never occur.
> This is where the analysis done by GNATprove comes in. It can be used to demonstrate statically that none of these errors can ever occur at runtime. Specifically, GNATprove logically interprets the meaning of every instruction in the program. Using this interpretation, GNATprove generates a logical formula called a verification condition for each check that would otherwise be required by the Ada (and hence SPARK) language.
Additionally, in Ada/SPARK, you can formally verify tasks (concurrency), too: https://docs.adacore.com/spark2014-docs/html/ug/en/source/co....
Moreover:
> SPARK builds on the strengths of Ada to provide even more guarantees statically rather than dynamically. As summarized in the following table, Ada provides strict syntax and strong typing at compile time plus dynamic checking of run-time errors and program contracts. SPARK allows such checking to be performed statically. In addition, it enforces the use of a safer language subset and detects data flow errors statically.
Contract programming:
- Ada: dynamic
- SPARK: dynamic / static
Run-time errors:
- Ada: dynamic
- SPARK: dynamic / static
Data flow errors:
- Ada: -
- SPARK: static
Strong typing:
- Ada: static
- SPARK: static
Safer language subset:
- Ada: -
- SPARK: static
Strict clear syntax:
- Ada: static
- SPARK: static
Additionally, safe pointers in SPARK: https://blog.adacore.com/using-pointers-in-spark and https://arxiv.org/abs/1710.07047.
More information about Get_Line (i.e. even where you would think you cannot go static): https://blog.adacore.com/formal-verification-of-legacy-code.
[1] overflow check, index check, range check, divide by zero
Already happening with Nim.
But I'd expect a system programmer to know better. When to use release and when to use development mode.
Case in point, rust doesn't catch integer overflows in release build either. Maybe Efficiency is more important than we think?
Maybe because they assume that it's only used for that purpose? You talk about rocket science and you expect people to jump on the bandwagon...
I look with interest to new languages but after so many years dealing with C, my parser crashes when I see the type after the variable name and at the end of functions declarations.
var x : u8 = 5;
What's wrong with "u8 x = 5;"?And I don't really like type inference very much (or when it's abused or cannot be avoided). What is "b"? Oh, I have to check what it's being casted from...
var a: u8 = 255;
var b = 1 + 2 + 3 - (4 + @as(i32, a));
What type is "b"? i32?Curious fact: the above code generates >40000 lines of assembly in godbolt: https://www.godbolt.org/z/fxfbb9jfn
I believe it makes the parser marginally more complicated. Let's say you had a non-builtin type, "foo". The var trigger immediately declares what's going on. For "foo x = 5;" the parser must either 1) have contextual information that foo is a declared type or 2) wait to notice that there are two identifiers side-by-side and then resolve that this means "it must be a variable declaration".
Honestly, C and C++ are very much in the minority for choosing this syntax. Coming form pascal, I remember finding this syntax to be annoying 20 years ago, so it's my bias to believe that this is just internalized pain for C devs.
As for the type coercion with the () operator... well, C is infamous for "spiral types". Typecasting complicated things in C, like, say, an array of pointers, can get scary as hell.
You want to be able to (somewhat) parse those so that you can syntax-colour, auto-complete, and mark errors in a code editor.
I think those are the major reasons modern languages don’t do such things the C way.
This would mean that the "peace of mind" of the Zig compiler developer has priority over my own "peace of mind". That's not ok.
Is the compile developer reasoning "I don't care if the syntax is verbose, messy (or whatever), it just makes my job easier"?
> Honestly, C and C++ are very much in the minority for choosing this syntax
Java, C#, Objective-C....
I took a quick glance at the ASM, and it seems that the majority of that is code from the stdlib run prior to main. Compiling with -OReleaseSafe brings that down to 15,000 lines of assembly.
If you get rid of "main" and compile it as an exported function, you get far less code: https://www.godbolt.org/z/jjGP4xsfx
If you add -OReleaseSafe to the "export fn" version I shared, it's around 4 lines of code calling panic. Adding -OReleaseFast, and it's just a ret statement.
I tried it with -OReleaseFast to compare, and it's 500-ish lines. That's amazing.
a *b
a * b
a[n] x
b [n]
a<x> y
a < x > y
e(1) f
e (1)f
Even for C/C++ this is complicated (you need the symbol table when parsing, to know if an identifier is a type or not), but for more advanced languages, it's even worse (e.g. if you support pattern matching / destructuring assignment).Declaring variables with var let's you also write let or const instead, giving the programmer more options (and making those options obvious as well).
You might not "like" type inference, but it really is superior to no-type-inference - you can always also write the expected type, if you want.
But you have to read the code of people who didn‘t.
var x = some_function();
What am I dealing with here? mmmmmm....Ok... let's find some_function()... I hope my editor has "go to definition", otherwise "grep -r some_function ."...
var x : u8 = 5;
allows making type optional while keeping the code about the same, e.g. var x = 5;
This arrangement has this nice consistency to it, with the type info being more of a hint (to the compiler or to the programmer) than a required component.Built-ins in Zig are functions beginning with `@`. Your cast operator would be a new syntax construct, something Zig tries to limit as much as possible (keeping the parser simple).
> What type is "b"? i32?
That's easy, i32. Integer literals are of type comptime_int, which may coerce into other integer types if possible without loss of information, and since the only typed expression is the @as, every other integer in the line will coerce to its type.
For code that is not yours, or code that you open a year later, I think it's easier to specify the type. Exactly as when you see something like "var x = some_function();" and you need to know the type.
The other gain here is with duck-typing as being less explicit allows you to write more generic code which will often do what you want as long as the shape fits without `void*` which gives up on type safety.
If you are reviewing code and can't instantly tell what the type is for a variable, ask the author to explicitly include the type. Problem solved.
That's because -Wconversion isn't part of -Wextra for some reason. It is part of -Weverything though, and with that clang does warn:
warning: implicit conversion changes signedness: 'int' to 'unsigned long' [-Wsign-conversion]
if (sizeof(int) < -1) abort();
~ ^~But sometimes the same value needs to be used in integer and floating-point math, and there is no single correct type for this value.
There are also some tricky choices in bit twiddling operations. Is it really such a problem when bits are shifted out of a value when this is normal behaviour down on the assembly level?
I guess I'll eventually learn to live with strict explicit conversion, and eventually I'll get better at picking the right type from the start, but I think implicit versus explicit conversion is an area where there is no "completely right" solution, because with 100% explicit conversions even coding down on the assembly level is more convenient ;)
I'm not quite sure if I understood you correctly, but in case you propose that integer <-> float conversion should happen implicitly I have to disagree. While implicitly converting from integer to float/double would probably be fine, implicitly converting from float/double to integer sounds like a recipe for headaches: There are just too many options (truncation/ceil/floor/rounding). Even if you decided that some option should be the standard since it makes sense in 90% of all cases (let's say rounding), you now have a difficult-to-find (since it's implicit) footgun ready to cause damage in the remaining 10% of all cases.
Even in that paragraph lies a small surprise waiting to be found (at least for some people): The floating point standard IEEE 754 defines five different rounding modes - two "normal" modes (Round to nearest, ties to even as well as Round to nearest, ties away from zero) and the additional directed ones mentioned above (truncation, ceil, floor). Interestingly, the default rounding mode (Round to nearest, ties to even) is not the one you probably learnt in school (that would be Round to nearest, ties away from zero). In school, you always round up if you end up exactly between two numbers, i.e. round(0.5) = 1, round(1.5) = 2. However, this introduces a small bias that can manifest itself into a real problem, for example if you round many measurements and then calculate the mean. That's why the default floating-point rounding mode will essentially alternate between rounding up and down, i.e. round(0.5) = 0 and round(1.5) = 2.
Most of the time this is not an issue and you really want the default rounding mode, but I hope this example illustrates why hiding the "implementation detail" of converting floating-point numbers to integers might not be a good idea.
By the way, I just looked up the man page for round(), and to my surprise found that it will always round ties away from zero, independently of the floating-point environment. If you want to round using different rounding modes in C, you apparently have to use nearbyint() and friends after setting up the rounding mode using fesetround().
PS: Of course the rounding modes are all about rounding floating-point values, not necessarily converting them to integers, but I think the point should be clear.
Mainly when working with pixels. In some contexts, pixels are clearly integer values (for instance the width and height of a texture in a 3D API is almost always given as integers, a texture with a width of 12.5 pixels simply doesn't make sense).
Computations on 2D pixel coordinates on the other hand need to have subpixel precision, otherwise you'll get jittering artefacts. This results in code where integer values must be converted to floating point before going into computations, and sometimes the results need to be converted back to integer.
I started to add duplicate functions to my C APIs to reduce the need for explicit conversions when using those APIs from stricter languages like Zig or Rust, for instance:
void sg_apply_viewport(int x, int y, int width, int height, bool origin_top_left);
void sg_apply_viewportf(float x, float y, float width, float height, bool origin_top_left);
PS: interestingly, even 3D-APIs don't agree here. For instance in OpenGL, the glViewport() function takes integer values, while in D3D11 and Metal a viewport is defined with floating point values. if x > 0
not compiling, because that's an integer zero, not a float zero! This makes the compiler feel very petty. if 0 == "0"
... which is obviously broken code.I guess it’s a matter of interpretation: does “x == 0” mean that we are comparing x with the integer zero, or the “zero value” of the same type as x? Numeric code is difficult for many reasons, but something that can make it much more tractable is having the code as close as possible to the mathematics underlying the algorithms, and this kind of “polymorphic constant” behaviour can help a lot, especially for integer literals which unambiguously embed into essentially any numeric type you could think of.
When you want to draw a pong game in a finite matrix representation, like a screen in ncurses, you cannot have something like screen[2.1][3.5], so you have to truncate (or round, depending what you want to do) the same float coordinates to write that matrix.
Of course, you could avoid these using fixed point but even there you need a type conversion.
I contributed to found the only discrepancy in D vs C code wrt integer (-byte would yield byte instead of int), and it was fixed so that they match exactly C _conventions_.
It result in things highly inconsistent on modern 64-bit machines:
For example, char/short are automatically promoted to int or unsigned int when an operation is performed on them, but this doesn't happen between int and long.
Simple things like adding two int16_t together to get a int16_t in return is really hard: you need a mask and a extra explicit cast, and you rely on the compiler being smart enough to understand what you are doing and to emit just the instruction you want.
But you don't need to do the same with int32_t, because reasons.
This is a bad default behavior, as it doesn't match either the intuition or underlying hardware, it is inconsistent across all integer types, and to understand why it works that way you need to understand how computers works 30 years ago.
D supporting C integer promotion might be a good thing for portability, but that's it.
The problem seems to be that (AFAIK) C stopped at 32-bit integers.
One issue with expanding all values to native word size is that this would manly benefit _very_ old hardware: modern CPUs are as fast directly manipulating any int size as they are manipulating "native word size", or even worse because vector instructions usually manipulate twice many int32 per cycle than they manipulate int64 (and twice many int16 as int32), even if not every code can be vectorized.
Because the first thing people will do is:
int16_t a, b;
a = (int16_t) ((b * 157) >> 12);
and then if b * 157 doesn't promote to 32-bit it overflows in the negative and then the code is incorrect. uint16_t a, b, c;
a = 50000;
b = 40000;
c = a * b;
This simple code may or may not have undefined behavior depending on the target platform. (it's fine for 16-bit int, UB for 32-bit int, and fine again for 64-bit int)Numeric promotion means that it's almost impossible to write code that is correct on multiple platforms with different sizeof(int).
I don't think so. A lot of existing C code relies on this, and removing the promotion will prime this code to be copy/pasted without fix. Who will rewrite all the C and C++ codecs code out there?
A lot of C and C++ programmers actually ignore the int promotion rule, but their code relies on it involuntarily.
There was more than enough time to learn why it was the right option to start with.
arr[i as usize]
This is actually risky, because even when you only meant to extend, you can also accidentally truncate or change sign. `as` does all of these things without a warning, and mixed with type inference it can easily lead to surprises.Rust makes it worse by insisting on a theoretical support for 16-bit and 128-bit `usize` regardless of the target platform, so you can't use `a[i.into()]` to infallibly convert `u32` to `usize` on 32-bit and 64-bit platforms.
The correct syntax is:
arr[usize::try_from(i).unwrap()]
which is painfully verbose. In larger expressions it's almost an obfuscation of what the code is actually doing.I think unsignedness on array indices is one of those places where the “make invalid states unrepresentable” mantra has gone too far: yes it’s nice that theoretically the whole 64-bit index space is addressable from a byte array based at 0, but in reality -1 is just as stupid and invalid an array index as 2^64 - 1 for pretty much every use-case. What we gain is negligible; what we lose is a lot of sensible code for dealing with index arithmetic.
#[inline(always)]
fn idx(i : u32) { usize::try_from(i).unwrap() }
or #[inline(always)]
fn get(arr: [T], i : u32) { arr.[usize::try_from(i).unwrap()] }
Have to repeat the definition for each numeric type you use, I guess, but hopefully you aren't using _that_ many of them.Personally, I have datastructure that uses non `usize` indexes I usually wrap my vector/array in in a custom type that implements index on whatever my common index types are.
Because everything else is "let" in disguise. ML got the syntax right.
Or not, you can also choose not to write these kinds of languages and nobody can blame you -- to each their own.
I know people are used to languages where compiler warnings are on by default, but if you are building C without -W/-Wextra you are kind of asking for trouble. -Weverything is probably too pedantic for most people but -Wextra is pretty much required. And -Werror is required for projects where discipline can't be assumed or where the build log is bigger than a screenful.
var x : u8 = 5;
var y = @as(u32, x);
OR var x : u8 = 5;
var y : u32 = x;
The cast is needed in the first case to force the inference y: u32, otherwise it would be y: u8Like, you saw it in the docs when you were mildly interested and decided it wasn't for you? Or you started a project, had at least a "hello world" compiling, but then eventually gave up on it because you were tired of casting? In that case I'm curious what the project was since I haven't run into casting all that often, but it might vary by domain.
Some people love typing code like they'd write books, i don't, i like to be concise and to go straight to the point
And it's not just as(i32) intToFloat(f32) floatToInt(i32), and then between i8 i32 i64, and then bitwise operations, and then slices, and then C strings etc etc etc, lot of visual bloat