3 ms·
foo({.x=2, .y=2}) I remember using this syntax in C in my 2017 project. This is very clear to call methods like that, I used it with minor #defines, i found th
by p0w3n3d 2y ago
foo({.x=2, .y=2})
I remember using this syntax in C in my 2017 project. This is very clear to call methods like that, I used it with minor #defines, i found the inspiration in the book "21st century C."
- sagarm 2y agoThe post mentions this obvious solution before delving into madness.
- harrison_clarke 2y agoi believe this is standard since c99 you do have to cast it, though: `foo((vec2){.x=2, .y=2})` the oldest MSVC on godbolt also accepts it, so it should be very portable as long as you're not using some embedded compiler from the mid 90s a related fun thing is that you can pass it by pointer, and the lifetime will extend until the function is done: `foo(&(vec2){ .x=2, .y=2 })`
- p0w3n3d 2y agoSmells like UB. Is this defined in the standard?
- harrison_clarke 2y agoC99 spec, section 6.5.2.5: https://www.open-std.org/jtc1/sc22/WG14/www/docs/n1256.pdf https://www.open-std.org/jtc1/sc22/WG14/www/docs/n1256.pdf > 6. The value of the compound literal is that of an unnamed object initialized by the initializer list. If the compound literal occurs outside the body of a function, the object has static storage duration; otherwise, it has automatic storage duration associated with the enclosing block. it's valid until the end of the block. so, if the function returns the pointer, you can even use that until the end of the block there's actually an example in the spec, on that page: > drawline(&(struct point){.x=1, .y=1}, &(struct point){.x=3, .y=4});