Programming in Modern C with a Sneak Peek into C23 - Dawid Zalewski - ACCU 2023

  Рет қаралды 100,356

ACCU Conference

ACCU Conference

10 ай бұрын

ACCU Membership: tinyurl.com/ydnfkcyn
accu.org
www.accuconference.org/
C Is Great, Long Live C! Programming in Modern C with a Sneak Peek into C23 - Dawid Zalewski - ACCU 2023
Slides: accu.org/conf-previous/accu2023/
If you are a seasoned C++ programmer you might think about C as a prehistoric language stuck in the times of K&R. But have you ever heard about compound literals and about how they can be used to enable default function arguments in C? Or have you ever used flexible array members to simplify dynamic data structures creation? What about anonymous unions, designated initialisers or static array arguments? Never heard of those? C is a living language that has much to offer to those who care about performance, who program close to hardware or whose daily routine involves interfacing C++ with C code. If you are such a person, or you are just curious and would like to learn about the older, little brother of C++, this is a talk for you. We will (re-)discover the perks and perils of modern C. Step by step, we’ll see how leveraging the latest language features helps readability, improves safety and leads to better runtime performance. Who knows, maybe you’ll find writing C enjoyable (again)?
---
Dawid Zalewski
Dawid is a computer engineer with a heart for teaching. He's been programming for over 20 years evolving through Basic, Turbo Pascal and many other languages to finally find his home in the land of C++ (with occasional visits to Python). His interests focus on the design and evolution of programming languages and paradigms. In his free time he explores the forming landscape of data-driven education or reads books.
---
KZbin Videos Filmed, Edited & Optimised by Digital Medium: events.digital-medium.co.uk
#accuconf #programming #cprogramming

Пікірлер: 198
@zxcaaq
@zxcaaq 5 ай бұрын
As a C++ programmer I find myself moving more and more towards C for performance and simplicity. C is truly a legendary language.
@KleptomaniacJames
@KleptomaniacJames 4 ай бұрын
I have been doing a lot writing custom libraries, and the amount of advice that is just "use the standard" really gets on my nerves. pointers take some getting used to, but they're not that hard. I don't need a std::array or a std::string sometimes.
@Matlalcueitl
@Matlalcueitl 4 ай бұрын
I tend to move in the other direction. I can write C++ code C-like, I can't write C code C++-like.
@lattehour
@lattehour 27 күн бұрын
as a C programmer i find myself moving more and more towards assembly for performance and deeper understanding of the computer and i hate that assembly with ardor horrendous thing full of demonic and unholy stuff that come from a warp dimension , very taxing on the brain but a inevitability if you try to really understand OS structure and programming , C++ still remains my preferred language
@henrikemppainen2511
@henrikemppainen2511 10 ай бұрын
C is one rare language where you can do the same thing for 15 years and be called modern. And I like that.
@michaelzomsuv3631
@michaelzomsuv3631 10 ай бұрын
15 is way low, most things in this video can be done already for 24 years =D The modern aspect is not about the features, it's about learning how to write good C with the features available in it since forever.
@iridiandot
@iridiandot 9 ай бұрын
Modern C has the same meaning as modern chess
@totheknee
@totheknee 8 ай бұрын
Rust is a common language where you can do the fad thing for 15 months and be called "modern," but still be a fad. We would be so much better off if people just learned basic programming skills in C instead of software "engineering" their way into a black hole with every new fad that comes along.
@illegalsmirf
@illegalsmirf 7 ай бұрын
Modern C has different syntax from older C
@nullptr.
@nullptr. 6 ай бұрын
@@totheknee Rust is a memory-safe language without a GC or a runtime, which mostly runs as fast as C/C++, so I would say that's pretty modern and fad indeed.
@dimitrioskalfakis
@dimitrioskalfakis 3 ай бұрын
back in the day (late 80s in a university environment) a unix administrator and resident c guru warned me not to be fooled by the small size of the language since i could spend the rest of my life learning new tricks and exploring its possibilities.
@Heater-v1.0.0
@Heater-v1.0.0 Ай бұрын
I first learned C in 1984, shortly after working a long time in assembler. I could not believe that there was a high-level language that was so sloppy, did not check anything much, did not give any warnings, just let your mistakes causes crashes and even bring down the whole machine in those day. Today I love C. It's minimal, the least "high-levelness" required to get one off assembler. It's small, one can can write a C compiler in reasonable time. It's best in class for performance. Today I also love Rust. Finally a high level language that banished UB and checks almost all silly mistakes I might make. While maintaining the performance of C and avoiding the monstrous complexity and ugliness of C++. And it interoperates with C very well. So I end up loving both C and Rust for polar opposite reasons. Rust will not replace C for me, they will coexist very well. I'm sure that is true in the wider world as well.
@JayJay-ki4mi
@JayJay-ki4mi 4 ай бұрын
25 year programmer here. I always knew C was a solid language, but I wasn't very productive in it. It gives you so much freedom, that without some knowledge of software design it can be difficult to build and maintain useful software. I learned so many languages over the 25 years, and it wasn't until I learned Golang and Rust that I actually understood how to design and build software correctly. When I came back to C, I had fresh eyes and I'm feeling like I can be productive in C. I'm still convinced C is the best programming language.
@BartaBO
@BartaBO 3 ай бұрын
if you want to do software correctly dont jump to hype like Rust, but use your head and learn Zig.
@foobar141
@foobar141 3 ай бұрын
Same here. I spend most of my career writing Ruby code, then moved to Go, and it made me want to try C. And I completely felt in love with it! It's now my main hobby language, although I'm sure the way I use it is unorthodox and nonsensical for professional C developers (I mostly write very small programs, sticking to UNIX idioms, and also lot of CGI programs, for use with my web interfaces). It just clicks for me, back to the simplicity we were aiming for in the very early days of Ruby (we failed quite spectacularly 😅), but this time I understand what's going on under the hood.
@kayakMike1000
@kayakMike1000 6 ай бұрын
I wish C had namespaces. I like those...
@ulfhedr
@ulfhedr 9 ай бұрын
"... so you can impress your colleagues!" This is the mentality where things go south usually. If anybody catches themselves writing "fancy", "abstract" code just so that you can impress someone, please take a good hard look into yourself because that's the opposite of what you should be doing.
@jamesnomos8472
@jamesnomos8472 4 ай бұрын
Have you ever heard of these fancy literary things called "jokes"?
@torsten_dev
@torsten_dev 10 ай бұрын
Designated array initializers are amazing and have a use. The trick here is that in the brackets you can use any constexpr expression, like enum values. So you can have a map from enum values to whatever you want.
@JB-iz8bi
@JB-iz8bi 10 ай бұрын
i love c c is best all hail c
@homelessrobot
@homelessrobot 6 ай бұрын
c doesn't totally lack type safety. C just has this feature called 'manual polymorphism' :)
@KFlorent13
@KFlorent13 4 ай бұрын
Are you referring to function pointers ?
@sproccoli
@sproccoli 3 ай бұрын
@@KFlorent13 im mainly talking about void pointers, but function pointers are certainly another way. especially if they take and return void pointers. (this is an alt account)
@GegoXaren
@GegoXaren 10 ай бұрын
This has been very interesting to watch. Thank you, Dawid Zalewski, for taking your time to make this presentation.
@AdityaKashi
@AdityaKashi 8 ай бұрын
This is a really fun talk!
@RyJones
@RyJones 9 ай бұрын
C has changed so much since I learned it in 86. C has barely changed since I learned it in 86!
@MaxAbramson3
@MaxAbramson3 2 ай бұрын
Do you mean that C++ has changed so much?
@scosminv
@scosminv Ай бұрын
C improved radically with minimum change... this is how I also see it :)
@Delease
@Delease 4 ай бұрын
What a fantastic talk. As someone who hasn't spent much time with C since college, this was very informative and entertaining.
@JorgeMartinez-xb2ks
@JorgeMartinez-xb2ks 5 ай бұрын
Thank you, I love C
@harinderbahra2996
@harinderbahra2996 4 ай бұрын
Very informative and entertaining
@YellowCable
@YellowCable 9 ай бұрын
There is a lot that has been presented I already use regularly in my personal projects, especially for clearer initialization; my priority is always about how to make the code more understandable, discoverable and debuggable though: so many creative uses of macros, old and new, are banned from my code.
@VaclavNemec70
@VaclavNemec70 10 ай бұрын
28:15 mapping enums on values for example
@stevejohnson1685
@stevejohnson1685 3 ай бұрын
Thank you very much for mentioning MISRA. I've been programming C (medical devices, automotive, telecom) since working at Bell Labs in the 1970s, love it, but your methodology, coding standards, and process determines the literal safety of the outcome.
@astarothgr
@astarothgr 9 ай бұрын
Good stuff!
@ACCUConf
@ACCUConf 9 ай бұрын
Pleased to hear that you liked the presentation!
@serhatarslan4138
@serhatarslan4138 3 ай бұрын
Even Beethowen wrote his Symphony in C
@slembcke
@slembcke 5 ай бұрын
Ooooh! I use designated initializers for arrays all the time for a couple of things: 1) I often make static tables of data that are indexed by enum values. You just [MY_ENUM_INDEX] = {.the = data, .for = it} 2) Graphics code often uses integers for binding slots, so I initialize plenty of complex nested structures such as: .targets[3].blending_mode = BLEND_ADD or something like that where different shaders need to set data to certain indexes deep within a large, mostly empty structure. Designated init works *great* for this!
@2002budokan
@2002budokan 6 күн бұрын
Best programming language that human kind invented.
@FaustoSaporito
@FaustoSaporito 9 ай бұрын
very good video, and the speaker was amazing :D
@ACCUConf
@ACCUConf 9 ай бұрын
Very pleased to hear your appreciative comments.
@BradenBest
@BradenBest 10 ай бұрын
45:35 the thing you're missing here is that these one-dimensional arrays "emulating" multidimensional arrays have several advantages over multidimensional arrays. A big one is that they are simpler and more efficient to allocate, deallocate and memset, since it is guaranteed to be one contiguous space. If you call malloc N times, then you have N spaces that are not guaranteed to be contiguous. As for not being able to understand it... skill issue. If you see the pattern enough times, y * width + x becomes obvious and idiomatic. Case in point, I understand that code perfectly fine. In fact, I find it easier to read and understand than the example you show soon after, where you create a pointer to an array of arrays and then collapse 3 layers of indirection into 1 in a cast at the end. I would not be confident that that would work if I were writing that code. The one dimensional pointer, on the other hand, is much easier to reason about, and you can easily write it in a way that it is more readable. You could collapse the size of a row into a constant called "width", or you could even make a macro to do the transformation from (x, y, width) to y * width + x. But when I see a pointer to array of array of scalar being cast to a pointer to scalar, that's a massive code smell to me. Very dirty cast IMO.
@BradenBest
@BradenBest 10 ай бұрын
I'm just gonna say this, and I'm not trying to be offensive or insulting, but a lot of the code shown in this video is code I would call "stinky". I think one of the worst examples would probably be the INVOKE macro. It's clever, sure, but it only works to switch between 2-arg and 3-arg functions. Try it on a 4-arg function and the macro generates text that attempts to call the fourth argument as a function. Try it on a 1-arg function and I'm not even sure it'll compile because this happens: `INVOKE(arg1, , function`. note the double comma. I think it's pretty clear that the macro should not be called INVOKE at all. It's too situation-specific and too much of a dirty hack. If it was called something like INVOKE_2or3, I probably wouldn't be complaining, or at least this comment would be seven sentences shorter. You also seem to think that modern C doesn't need to cast malloc, as opposed to "old" C. Well I'm here to tell you that C has always been weakly typed and casting a void pointer to a non-void implicitly has been allowed ever since void was first introduced in C89. Before void pointers were a thing, malloc returned a char*, but I don't think it was casted then, either. Again, C is weakly typed. Some other examples of patterns you use that I don't like are typedefing structs (never do this, just use the struct keyword, it's clearer and easier to read) and that [static 1] thing. Both because it puts brackets in the function parameters and because it's telling the compiler to literally throw the whole program in the trash because a null pointer gets send to the function. In my opinion, it's the callee's responsibility to handle that case gracefully. And it's not hard to do in a way that is readable as long as you structure your if statements appropriately. If you are putting 98% of the function in a single if statement, you are doing it wrong. Invert the if and early-return, get rid of that unnecessary indentation and unnecessary complexity. It was an interesting video, but you and I clearly have very different ideas on what modern C looks like. I shouldn't be surprised because obviously you are a C++ programmer first and a C programmer second. I gather this from you casting malloc in that refactoring segment and calling it "old C" and from you disappointedly saying that C doesn't have name mangling, as if it would be a good thing to add that crap to the language and make compilation slower. It's ironic because earlier in the video you quote Torvalds on VLAs, but if you knew Torvalds, you'd know he hates C++ and frankly, if you submitted code that looks like what you showed in this video (especially that kernel related one that I touched on in the parent comment) to the kernel source tree, Linus would absolutely cuss you out.
@scpmr
@scpmr 9 ай бұрын
int (*arr)[WIDTH]=malloc(sizeof(*arr)*HEIGHT); is also continuous in memory, you call malloc 1 time, and you use arr[y][x] instead of arr[y * width + x]. And it's not a new feature. It always was possible.
@xhivo97
@xhivo97 7 ай бұрын
I think the VLA syntax is a good idea in theory but I _wish_, badly so, that it worked better with sanitizers vs. just a pointer. I tested this a bit and it's better than just a pointer but it's not perfect so, eh, I am really conflicted if I should use this or not. You could always use macros to index into them, and such a macro is cleaner and a good use of a macro IMO. So basically, I wanna love this but I can't yet unless clang and gcc (or is the sanitizer standalone) add exclusive benefits to this syntax. I will add though, that in practice if you're careful it wasn't as error prone as you'd think. My use case was casting an void* to int[x][y]. I think something like int a[2][2] = data; was good enough for me IIRC, this was awhile ago. edit: I tested this out, and yup, VLA syntax + sanitizer on on your compiler catches all the out-of-bounds UB in my tests, while a classic pointer style syntax doesn't catch any when passed to a function.
@tomaszstanislawski457
@tomaszstanislawski457 10 ай бұрын
Great presentation. I think that the presenter should more real application of modern initialization in C. I suggest showing how compound literals (CLs) combined with designed initializers can simplify setup of complex tree of structures in Vulkan API. No need to create a bunch of auxiliary object and vectors. Just taking address of CLs or CL arrays gets the job done.
@onaecO
@onaecO 4 ай бұрын
Love C
@chalimsupa6603
@chalimsupa6603 29 күн бұрын
Long live C.... the grandfather of all programming languages!
@l_t_m_f
@l_t_m_f 10 ай бұрын
Amazing video with lot's of insights.
@ACCUConf
@ACCUConf 9 ай бұрын
Thank you for your appreciative comment!
@alexoverstreet
@alexoverstreet 5 ай бұрын
You know there’s a problem when the format for your talk about why C is great is a quiz on how confusing C semantics are.
@epsi
@epsi 3 ай бұрын
1:08:46 The semantics associated with flexible array members are a bit weird. They're arrays of incomplete of an incomplete type, but one can use a compound literal to initialize the structure, so long as the flexible array member remains uninitialized. However, a flexible array member has no presence in the language itself aside from being a named field in a structure: it has no size itself, and it has incomplete type, so you cannot initialize it, yet you can still refer to it, and get its address. Also, the allocation is simplified to sizeof(string_s) + sizeof(char[len+1]) because there is assumed to be no padding between the length field and the flexible array member. If you add another field of type char between the two, you may find that the offset of the arr field is less than the size of the entire struct due to padding at the end, resulting in allocation of unused bytes. To use every bit of the space, you need to allocate the maximum of either sizeof(string_s) or offsetof(string_s, arr) + sizeof(char[len+1])
@astralfoxy1787
@astralfoxy1787 7 ай бұрын
@18:50 Is it right? Looks like a no check for NULL ptr in this example and only warning for arrays with [0] size as expected.
@Je3f0o
@Je3f0o 9 ай бұрын
This talk is very interesting and i cannot program in C while listening. So I’m gonna watch this later. :P Btw i’ve been programing more than 15 years 20+ programming languages and now days programming back to C and Rust.
@alvaronaranjo2589
@alvaronaranjo2589 4 ай бұрын
Cool. I’m getting back into C after a decade or so.
@user-gh4lv2ub2j
@user-gh4lv2ub2j 4 ай бұрын
I had to wait 6 months to find this??? I'VE BEEN INITIALIZING STUFF WRONG FOR 6 MONTHS NOW!?!??! The shame, oh the shame!!!
@austinhastings8793
@austinhastings8793 5 ай бұрын
One change I would like to see in C would be to add a syntax like [*]= in array notation to allow for a "default to something other than zero" mode. Something like `double array[10] = {[1] = 3.14, [2] = 2.78, [*] = 6.02e23};`
@vytah
@vytah 4 ай бұрын
If you mean your * has to become 3, then you write this as {[1] = 3.14, [2] = 2.78, 6.02e23}. The elements without indices follow after the last element with an index.
@stackercoding2054
@stackercoding2054 4 ай бұрын
then you are looking for a dictionary or a hash table, not an array
@kenneth_romero
@kenneth_romero 4 ай бұрын
Finished Effective C recently and started to do some advent. Man does it feel so nice to use the more modern features. It reminds me of a more stripped down Zig.
@michimarz
@michimarz 9 ай бұрын
I don't like generics, INVOKE macro trick, and constexpr. I'm not sure about bool. The rest seems worth a closer look.
@lattehour
@lattehour 27 күн бұрын
15:42 that int (*pk)[ sz ] [ sz ] has the *pk in parenthesis because the array operator [] has higher precedence IF the parenthesis where not to be used you will have double array full of pointers to int which is a totally and completely differnt thing from a pointer variable , more so it will invalidate the malloc call , further reasoning *pk is a pointer to int therefore Encapsulates information about the data object aka int which is a 4bytes (32bits) this encapsulation/metadata if you want to call it such is what allows the pointer arithmetic to be performed it makes the pointer aware of the data object therefore when you add/sub 1 from it it will Move the instruction pointer registers exactly 4bytes using a LEA instruction it is extremely fast
@rezakghazi
@rezakghazi 5 ай бұрын
C programming language is a tool and the quintessential soul of computer architecture and foundational programming. It is akin to an elemental force that underpins the very fabric of computing, transcending mere syntax or semantics. This soul, deeply ingrained in the computing structure, migrates through various embodiments - from operating systems to embedded systems, manifesting its presence in numerous forms, much like an incarnation. Each new form it takes on, be it a simple microcontroller or a complex operating system, is endowed with the essence of computational logic and efficiency that C embodies. Just as a body may function with limitations but cannot exist without a soul, so too can modern computing operate with various languages and tools, but it cannot escape the fundamental principles and efficiencies ingrained by C. This language embodies more than just a set of instructions; it represents computational thinking and efficiency, acting as a cornerstone that builds the edifice of modern computing.
@andrewpelletier1199
@andrewpelletier1199 4 ай бұрын
😊😮 Bravo! ChatGPT or Bard....... or, You ?
@GilbertLaurel
@GilbertLaurel 9 ай бұрын
Nice!, can we compare it with C3Lang
@2002budokan
@2002budokan 6 күн бұрын
Every time he says, "It's like in C++", I say, "Oh no"; "Oh no, they will make C look like that".
@10e999
@10e999 9 ай бұрын
Either I don't understand or I found a bug at @45:45: In the line *(pK + i*sizeof(double[sz])) + j) = _gcoeff(sz, i, j) sizeof(double[sz]) is only valid if your pointer was a char*. it won't work because pointer arithmetic is performed relative to the base size.
@the_original_dude
@the_original_dude 6 ай бұрын
sizeof(double[sz]) is sizeof(double) * sz
@anon_y_mousse
@anon_y_mousse 3 ай бұрын
@@the_original_dude Yep, and he's right, it's a bug.
@Paxsali
@Paxsali 10 ай бұрын
at 31:45, section "Static vs. dynamic?"... why not use "int* numbers = malloc(sizeof(int[a_lot]));" instead of "a_lot * sizeof(int)"?
@Paxsali
@Paxsali 10 ай бұрын
Forget about it, my question what answered at 45:33.
@dave_oleksy
@dave_oleksy 10 ай бұрын
Are there any reference/resources (i.e., books, blogs...) that describe Modern C (besides the standard itself)?
@chmod0644
@chmod0644 10 ай бұрын
Seacord's book Effective C
@dickheadrecs
@dickheadrecs 10 ай бұрын
i’d love to know this
@xBiggs
@xBiggs 10 ай бұрын
Modern C by Jens Gustedt is the best reference. I don't think it covers C23 yet though
@Muhammed.Abd.
@Muhammed.Abd. 10 ай бұрын
Book: Modern C by Jens Gustedt
@rurban
@rurban 10 ай бұрын
There's not much in C23 to add to his book. C26 should have proper strings, maybe
@totheknee
@totheknee 8 ай бұрын
46:00 - Is it really that bad? I remember trying to wrap my head around multidimensional arrays in BASIC when I was 14. But it's always `row*stride + col` for 2D. Always. It isn't that hard, right?
@TomPomme
@TomPomme 6 ай бұрын
Yeah it's not, he also wrote that down unnecessarily complicated. Instead of *(pK + i*sizeof(double[sz]) + j) = _gcoeff(sz, i, j); it's just pK[i * sz + j] = _gcoeff(sz, i, j);
@anon_y_mousse
@anon_y_mousse 3 ай бұрын
@@TomPomme Yep, it's actually a bug since he's using a double* and the compiler would automatically multiply the index by sizeof(double), so he's using the stride wrong. He was probably writing up an example using unsigned char* and decided after he'd written it that it'd be better to properly type it and forgot to delete that.
@astralfoxy1787
@astralfoxy1787 7 ай бұрын
57:01 - Looks like a UB. Compiler will destroy our "NULL check" (Why even need that if "free" do nothing with null pointers) or destroy dereference of a null ptr at line 7.
@anon_y_mousse
@anon_y_mousse 3 ай бұрын
Yeah, the clearing should be done in that `if` block where he makes sure that `pa` points somewhere. As for checking that `data` points somewhere before calling free(), I just assumed that he's been using it on embedded platforms where the function call to do nothing would take more processing time than a local branch to test against NULL.
@ivanpribec3353
@ivanpribec3353 5 ай бұрын
I still find that Fotran dynamic multi-dimensional arrays (allocate(pK(sz,sz)) and an intuitive access syntax, pK(i,j), much easier than this VLA syntax.
@whyis2plus2
@whyis2plus2 6 ай бұрын
Can't wait for it to become common place in 2069
@nunyobiznez875
@nunyobiznez875 4 ай бұрын
45:35 That's a mess because it's not correctly allocated as a multidimensional array. It's only being allocated as a single dimension, which will work, but it's a mess and/or behaves as a single dimension. If you want a multidimensional array, it really should be allocated multidimensionally. Which is to say, allocate your first array dimension and assign it to a **ptr. Then use a for loop to step through each element of the array, assigning a pointer to it for another allocated array of the desired size of your next dimension. Then it will behave as a normal multidimensional array, using standard arr[col][row] notation. No VLA's required. It just has to be freed the same way it was allocated. Example: #include #include int main(void) { int i, j, col = 5, row = 5, **arr = NULL; arr = malloc(sizeof(int *) * col); for(i = 0; i < col; ++i) arr[i] = malloc(sizeof(int) * row); for(i = 0; i < col; ++i) { for(j = 0; j < row; ++j) { arr[i][j] = 'A' + i + j; printf("%c ", arr[i][j]); } putchar(' '); } for(i = 0; i < col; ++i) free(arr[i]); free(arr); return 0; }
@doBobro
@doBobro 3 ай бұрын
It's very naive approach to multidimensional arrays. Access speed is shit, alloc speed is shit. You could drop basically anything you have been taught in uni regarding C and C++.
@anon_y_mousse
@anon_y_mousse 3 ай бұрын
That's downright horrific. The better method is to allocate for the first dimension and the second in one allocation then patch up the pointers of the first dimension. It still requires a single loop for 2D arrays, but only one malloc()/free() per 2D array. Also, you should put it in its own function and do some basic error checking. Of course, most would recommend using a 1D array and just indexing by [i*w+j] instead of doing something so insane.
@soniablanche5672
@soniablanche5672 3 ай бұрын
single dimension arrays emulating multidimension arrays are way faster than having to go through pointers to get the data
@tolkienfan1972
@tolkienfan1972 5 ай бұрын
Can the standards committee please, please, please remove the implied "promotion" of short unsigned types to "signed int"? It only caused bugs
@galier2
@galier2 4 ай бұрын
The program at 17:00 is malformed, but for none of the reasons listed. The main function is a function and requires to return at least 0 or 1 (EXIT_SUCCESS/EXIT_FAILURE) statement.
@Nate-dz8wq
@Nate-dz8wq 4 ай бұрын
Check out www.open-std.org/jtc1/sc22/wg14/www/docs/n3096.pdf , section "5.1.2.2.3 Program termination"... It reads: "... reaching the } that terminates the main function returns a value of 0". I think this was added in C99, but may be off on the history...
@smergibblegibberish
@smergibblegibberish 3 ай бұрын
C99 and onward let you imply return 0 from int main.
@anon_y_mousse
@anon_y_mousse 3 ай бұрын
Why are you assuming that those are the values of those macros? The standard doesn't define them, and they could be 0 and 1, or they could be -22 and 33. In fact, the wording they use for describing how exit() works is grammatically ambiguous and could imply that EXIT_SUCCESS couldn't be 0, but either way, the host system may very well take any value and exit() would be required to convert to that value for a successful exit.
@anon_y_mousse
@anon_y_mousse 3 ай бұрын
Interesting talk, but there are a few errors. Around the 16:30 mark, he said that program was well formed, but he should have only said that it compiles. Using a magic number for the size of a buffer is a huge problem, but he didn't check the return value from strftime() which could lead to weird bugs and/or a segfault. The slide around the 18:15 mark was all kinds of wrong. The accept() function in that example only took one argument, not multiple. This may be a language barrier issue, but he should get someone to revise the text, and he misspoke with regards to what static meant in the argument, as it required *at least* 1 value to be in the array. One could attempt to rationalize that as enforcing a C-string, as in a nul-terminated array of char's, but it wouldn't do that as you could pass the address of a single char and it could be set to anything. The two slides at 23:00 and beyond have a weird comment that seems to equate zero initialization of a char * to the value "" which is incorrect as that would have it pointing somewhere and only a tiny percentage of niche systems allow data to be stored at address 0, which is why that was chosen as NULL. I still don't get why C needs a nullptr constant when we already had NULL, and if it's about casing, why do we need the `ptr`. If it's a type checked thing, then again, why `ptr`. This also relates to the addition of constexpr as I'd rather they just change the functionality of const but also, I'm not averse to defining macros inside functions and regularly do so, especially when it's just for that function, and aside from that, if it's about type checking, constant values can use type postfixes and there's always the standard #define SZ ((size_t)100) to give it a particular type, if you don't know the correct postfix. At 33:00 I actually agree regarding VLA's and generally try to avoid using them, but there are legitimate use cases since they allocate on the stack, and I would definitely avoid using a maximum allocation size for every use of one. Given that the stack is generally limited, it'd be better if the max value was dynamically checked either way, but if you need that much space that it would blow the stack then use the heap instead. Around 46:00 I would just use i[*pK][j] to avoid needing the extra set of parentheses. I still don't understand why so few people use this superior approach to referencing arrays of data to avoid LISP-ing your code. As for 1:07:00 and flexible array members, I find that generally it's better to not use them. It adds hidden complexity to structs and does prevent you from making arrays of them or taking the sizeof them, and embedding in other structs and yes, even directly initializing them. If you're worried about multiple allocations then use the strategy I employ where the container is allocated on the stack. While the separation is a valid concern, it's an overblown one for certain types, especially when we're talking about large data sets. The data will dictate more how it should be accessed than the few pieces of bookkeeping information, and from an ergonomics standpoint, you shouldn't be allocating for a single container on the heap ever.
@stackercoding2054
@stackercoding2054 2 ай бұрын
I've been a JS/Python soydev for the past 5 years, basically because I learned to code specifically to work as a developer rather than to learn about computers. The last 6 months I've been coding multiple personal projects in C and I feel like I have a superpower now, I understand a lot of low level stuff that the high level languages hide and my code skills are much better. Probably learning C was the best decision I could make. I feel like I want to stop being a webdev because I'm sick of it, but I don't think I have the skills yet to apply for a full C/C++ job, that's gonna be a long ride.
@kees-janhermans910
@kees-janhermans910 24 күн бұрын
Compound literals, don't they also exist in Java for example?
@ndotl
@ndotl 4 ай бұрын
tl;dr: I am looking for good old fashioned (hardcore) C and C++ books that are current (e.g. 20 or 23). I have an MSCS degree (with EE undergrad). I think it is one of the reasons I find efforts to dumb down the material mind numbing. Most of my learning has been through textbooks, and the Java/Salesforce developer guides provide a good textbook-like in-depth coverage of major topics. P.S: Happy holidays. Long version: Can anyone suggest good C and C++ books? I have not really coded in either for over 10 years. It has been Java and Salesforce (Apex) during that time. I post the above question because I am not able to find a good C++ book. I think the textbook-like book from Stroustrup would be OK if it was current. The Murach book seems like it is targeting learners who are new to programming. I find the pattern of material presentation mind numbing. To me it seems that to get a deep understanding of a subject you need to go through 10 mini-tutorials. And the video tutorials are no better.
@nicksalvador9729
@nicksalvador9729 3 ай бұрын
I havent programmed in C myself since college, however my friend was recently learning C and Lisp. He used the books "The C Programming Language" by Kerrigan and Ritchie. For learning Lisp he used "Structure and Interpretation of Computer Programs" by Harold Abelson, Gerald Jay Sussman, and Julie Sussman. Even if you are not interested in Lisp, the book contains important concepts for understanding and learning programming in general. Also there are Python and JavaScript versions of "Structure and Interpretation" if you are more inclined to those languages. I hope this helps.
@angelcaru
@angelcaru 11 күн бұрын
I don't know if I love or hate the fact that the only people using C nowadays are Python devs
@meandtheboyz4796
@meandtheboyz4796 5 ай бұрын
when are we getting rid of header files?
@soniablanche5672
@soniablanche5672 3 ай бұрын
Do you even know what a header file is ? You can literally replace all you .h file with .c and it will still do the same thing they are called "header" for organization purpose, header files themselves are C files
@not_herobrine3752
@not_herobrine3752 10 ай бұрын
i think ill start using k&r after this
@KANJICODER
@KANJICODER 10 ай бұрын
I am with you on this. C's selling point is that it is a very small language that can be easily memorized. It is what sets it apart from all other languages. If people INSIST on adding to a language FOREVER with no stopping point, the language is eventually going to hit a critical mass of un-maintainability where no one in the world can write a compiler for it. C might be furthest from that future, but doesn't mean we should march towards it.
@VaclavNemec70
@VaclavNemec70 10 ай бұрын
yeah, I loved the old function syntax, I don't understand why they removed it 😭
@autistadolinux5336
@autistadolinux5336 9 ай бұрын
I'm sticking with C99, actually.
@FredBakker
@FredBakker 5 ай бұрын
What! Are they trying to make C safer? Move responsibility from the developer to the compiler? Have they gone mad?
@turdwarbler
@turdwarbler 5 ай бұрын
I was taught C in 1981 as a new grad in Computer Science when working for a company called ARBAT by my boss Peter Madams. Best boss I ever had. We used Whitesmiths C on a PDP-11 and later on a Vax. 42 years later I am still using C/C++ in the financial trading industry, so I am very lucky that it has given me my whole career. My boss used to say, "There is no such thing as a correct C program, just one that has never gone wrong yet !!" This is as true today as it was in 1981.
@abhinavk0929
@abhinavk0929 10 ай бұрын
Does int a = {5.8}; work in C or not? In c++ ( without the equals sign) it would error out due to narrowing conversion, is it same in C or C does the conversion anyway?
@michaelzomsuv3631
@michaelzomsuv3631 10 ай бұрын
Of course it works. Well, the only reason why this would not work is if you have conversion warnings enabled + warnings as errors, then you would have a compile error. Other than that, it works.
@Ak4n0
@Ak4n0 10 ай бұрын
Yes, it works. `int a = {5.8}` is the same as `int a = 5.8`, C truncates the decimal part and returns the integer part.
@aasquared8191
@aasquared8191 10 ай бұрын
a narrowing conversion is definitely a warning, not an error.
@hemerythrin
@hemerythrin 10 ай бұрын
It doesn't error on gcc trunk at least, and I don't think the standard requires it to error either. But there's always -Werror=conversion
@4otko999
@4otko999 10 ай бұрын
If designated initializers work differently in c and c++, but c++ is supposed to compile c code, does that mean that eventually requirements for designated initializers are going to be relaxed in c++?
@your-mom-irl
@your-mom-irl 10 ай бұрын
No. C++ isn't strictly a superset of C, never was. C++ won't change anything just because C2X wants to add a feature or whatever
@maksymiliank5135
@maksymiliank5135 10 ай бұрын
C++ is no longer just a superset of C. There are things which are different in C++ and C. For example the auto keyword or function declarations with no parameters. Edit: After watching the talk, it turns out that the auto keyword behaves exactly the same as in C++
@sleepy-monax
@sleepy-monax 10 ай бұрын
> c++ is supposed to compile c code It's not, C++ isn't a strict superset of C
@aidangarvey7049
@aidangarvey7049 10 ай бұрын
Maybe, but C++ isn't always able to compile C code so C++ might keep its stricter rules. For example, `auto float` in C is a valid way to declare a float, but in C++ it won't compile because auto always stands in for a type name
@BradenBest
@BradenBest 10 ай бұрын
No, and the reason why is because C++ is not, never has been, and never will be, a superset of C. Try assigning malloc to a pointer without casting in C++ and tell me how far you get. Better yet, try to compile literally any real-world C program in a C++ compiler. They won't compile. Funnily enough, Python code also won't run in a Lua interpreter. Nor can MASM compile Java. The answer is simple: use a C compiler to compile your C code.
@__gadonk__
@__gadonk__ Ай бұрын
my rule of thumb is. If a macro changes the C syntax, you shouldn't use it
@mychromebook9935
@mychromebook9935 9 ай бұрын
C is just better than rust and I love it.
@jakubsebek
@jakubsebek 9 ай бұрын
Better in what sense?
@bassyey
@bassyey 9 ай бұрын
All the hype around rust but barely anyone uses it in embedded. I've work HDD and SSD firmware. I wrote how these things operate. Written in C. Worked in SIM cards, credit cards, NFC cards, firmware is written in C too. My friends from the industry, cars head unites, POS, and lot more, C. It's C, C, C.
@zheil9152
@zheil9152 8 ай бұрын
@@jakubsebekit’s actually used in production
@rt1517
@rt1517 9 ай бұрын
I am probably an old retarded. I don't find much of "modern" C attractive. Maybe I am allergic to changes. I think one of the main advantage of C is that it does not change that much. So that both old and new code can be compiled on both old and new compilers (if you are lucky). And so that C remains simple to learn. And writing a compiler remains simple. Don't get me wrong, there are a lot of things that I don't like in C, for example the #include mechanism which basically implies slow compilations, some of the undefined behavior stuff, some aliasing rules which force the compiler to generate instruction to re-read unchanged memory... But adding an initializer that sets non referenced fields to zero? That sounds against C principles. Non-referenced fields should not be initialized. C is not Java or something. And the sizeof a struct with a VLA inside that returns the size of the struct ignoring the VLA... That sounds weird, almost buggy. And [static 1] for non-null looks awful. It would be nice to be able to define if a function can or cannot take null in one of the argument. But it should look a lot more straightforward, like a nonnull keyword or something. Or better, the other way around, a null keyword.
@VV-rk3wu
@VV-rk3wu 5 ай бұрын
A lot of this talk was slightly horrifying for me... (with due respect and thanks to the presenter for the whirlwind tour of the new features!) but syntax which means different things in different situations, or expressions that are jokingly "confusing" but the compiler accepts... these are the sorts of things that squeak through code reviews and will absolutely cause serious bugs. The C and C++ committees both are aware that these languages have a reputation for complexity and tricky shoot-yourself-in-the-foot gotchas. The goal should be to simplify the murky areas of syntax or to only introduce syntax that is very cleary distinguished from other & previous rules, and does what you would intuitively think it does, not something "surprising" or quizzical (literally). This talk demonstrates the committee is going in the opposite direction, introducing more and murkier syntax rules and surprising implicit/contextual semantics. Also, what if I need to have two VLAs at the end of a struct? 😅
@makara2711
@makara2711 4 ай бұрын
finally a comment i can fully agree to!
@anon_y_mousse
@anon_y_mousse 3 ай бұрын
I'm curious as to what aliasing rules you're talking about. If you mean evaluation of macro arguments, well, that's annoying but also a symptom of bad macro writing. If something else, then please expound upon what they are. C99 added the ability to zero initialize entire arrays and structs with { 0 } and extending that only makes sense. You can't use a VLA in a struct definition. The term is flexible array member because the size isn't defined at all. Pre-C99, a lot of code would use [0] for the array size and just allocate the extra space as needed, but you can literally use any non-zero size you want and do the same thing, just with a default minimum. I will agree slightly with the static keyword in an array argument, but I'd prefer no keyword and instead to just use [1] to indicate that it requires at least 1 element. That would change the meaning of that construct, and I don't care. The only alternative that I would accept is to use something like [>=1] or [>0] or maybe even the more ambiguous [1?].
@anon_y_mousse
@anon_y_mousse 3 ай бұрын
@@VV-rk3wu I'll tell you what I told the other guy, FAM, not VLA. But if the two arrays you wish to place at the end are the same length, then struct the two types and use one array of both together. If they're differently sized, then either one's a pointer and the other a FAM, or they could both be pointers and make things safer. Also, you should be allocating containers either together on the heap or singularly on the stack.
@harryshuman9637
@harryshuman9637 19 күн бұрын
The new features are neat if they will help reduce issues without requiring modifications of the existing code. But things like that non-NULL check are wack, if you start introducing those things you might as well recompile your code in C++ with use of references if needed. Not sure why they decided to make non-NULL argument descripton so complicated. It makes literally NULL sense.
@fdc4810
@fdc4810 10 ай бұрын
May I ask why line 4 in 15:51 works ? I thought an array definition would ask the compiler to automatically allocate the memory on stack, with size corresponding to the type and number of element it has ? And can someone also explain line11 in 17:51 ? 😂
@tomaszstanislawski457
@tomaszstanislawski457 10 ай бұрын
Because it declares a pointer, not an array. Think about line 4 as `typedef int T[sz][sz]; T* pK = malloc(sizeof *pK);`. The array type is defined and next a pointer to this type which is used to allocate object on heap.
@Ak4n0
@Ak4n0 10 ай бұрын
1. pK is just a pointer. The type of this pointer is an array of 'sz' arrays of 'sz' ints. Since it's just a pointer, it needs malloc to obtain its memory chunk. Before the '=', the data type has been defined, so C already knows the size it's going to have. That's why sizeof(*pK) can return that size in bytes. 1. 'auto' is a data type inferred by the compiler from the expression on the right side of the '='. Remember that (char [42]) is the same as (sizeof(char) * 42). (char [42]) is the cast of {}. {} is a portion of memory on the stack, which, due to the cast, will have a size of (char [42]) bytes.
@metamaverick
@metamaverick 10 ай бұрын
The type of line 4 is a pointer so it’s storage is simply the size need to store an address, so like 32 or 64 bits. But this pointer is given additional metadata about what it is pointing to. We know the type of the elements are “int” and that it points to a 2 dimensional array of equal height and width (sz). This means sizeof(*pK) is asking not for the size of the pointer but the data that it is intended to point to and thus resolves to sizeof(int)*sz*sz. If we assume, as he did/noted, that an int is 4 bytes this gives us 400. Line11 is definitely an weird one, since he says it works my only rationale is that it is declaring “buffer” as 42 character array and not specifying an initializer value for the elements in the curly braces . Definitely bad style, I hope I never see such code in the wild.
@hemerythrin
@hemerythrin 10 ай бұрын
For the first question: it's a pointer to an array. So it won't allocate the array on the stack, just a pointer. Same way that int *x won't allocate stack memory for an int. Second question, it's equivalent to char buffer[42] = {0}; (char[42]) {} is an array literal of 42 chars, initialized to zero. auto buffer = ...; means assign ... to buffer, and infer its type. So in this case the type will be inferred as array of 42 chars, and it will be assigned the value of 42 zeros.
@elekid2901
@elekid2901 10 ай бұрын
At 15:51 `int (*pK)[sz][sz]` is a pointer to a 2 dimensional variable size array, so when when `malloc`ing you wan't to have the size of the 2D array and not the pointer, that's why he dereferences `pK` in the `sizeof()`. At 17:51 in line 11, he creates a `int` variable (no type is specified, so defaults to int) `buffer` with storage duration `auto` and assigns it the pointer to the first element in the zero initialized `char` array. (Arrays in C and C++ automatically decay to pointers).
@MustaphaRashiduddin-zx7rn
@MustaphaRashiduddin-zx7rn 5 ай бұрын
listen i'm either gonna stay at c99 or just go to zig
@verdantblast
@verdantblast 9 ай бұрын
it's indeed a great video a great video to keep me away from c...
@rolandinnamorato1953
@rolandinnamorato1953 7 ай бұрын
oh nice a new standard i will never use
@colinmaharaj
@colinmaharaj 9 ай бұрын
3:12 auto is for not specifying the storage type. Lol😂
@frankgerlach4467
@frankgerlach4467 4 ай бұрын
C is the language which created the Cyber War Domain. The Hamburger+Cola of computer science. There have always been much better alternatives around: +ALGOL +PASCAL +MODULA-2 +ADA Plus some newer ones such as RUST and SAPPEUR.
@chrimony
@chrimony 9 ай бұрын
@12:53: Wow, so C23 made even more ways to get silent errors. Lovely! Compile your program in the new version, get different answers! Brilliant!
@grafgrantula6100
@grafgrantula6100 9 ай бұрын
No, in this case C23 fixes weird behavior, where the new C23 output is what a sensible person would expect and the old output is an arcane artifact. I like this change!
@xr.spedtech
@xr.spedtech 10 ай бұрын
I'm trying everything here except for the auto keyword.
@Kobold666
@Kobold666 5 ай бұрын
The auto keyword is as old as the C language. It's just the opposite of static and tells the compiler to allocate a local variable on the stack, which is the default option anyway (auto, static, register). It has a very different meaning in C++.
@0xAtari
@0xAtari 9 ай бұрын
The truth is that programmers have to make a living and the market dictates demand for emerging languages such as Rust. In 5 years time there’s a suspicious chance that Zig will paint a great picture.
@lesterliston4692
@lesterliston4692 9 ай бұрын
When javascript creator disclose his technique. Just my opinion.
@b213videoz
@b213videoz 5 ай бұрын
Turbo Pascal is much, much better 😊
@autistadolinux5336
@autistadolinux5336 9 ай бұрын
Huh, never thought on using VLAs as an argument. I always thought it was just a retarded feature.
@Evan490BC
@Evan490BC 5 ай бұрын
Is "Modern C" analogous to "Modern Ancient Latin"?
@ShaopengChen
@ShaopengChen 4 ай бұрын
All these new features but just more confusion. What a missed opportunity! Speaking as someone who had worked with C and C++ in telecom industry for over 10 years. If you have a large team but without a very strict coding style and do not enforce it strictly in code review, you would have a big mess. Have not used these two languages for more 15 years. After watching this presentation, I can't say I miss them.
@Spongman
@Spongman 9 ай бұрын
automotive safety... we don't care about types.
@jarvenpaajani8105
@jarvenpaajani8105 4 ай бұрын
I don't know man, this whole video feels like mocking C, showing whats wrong with it and still saying it's great.
@ElPikacupacabra
@ElPikacupacabra 9 ай бұрын
I don't like this talk. If you hate the language, why speak so much rubbish about it? So much FUD being spread about features that have a clear purpose and give a lot of flexibility. I think the author really likes to use something like Rust, or some other safe language, on a powerful machine. And he should stick to that. Case in point: VLAs. You don't have to use them if you don't like them. There's even a flag to turn them off. But in certain applications you do NOT have to check the size of the array, you need the space saving, and you don't have the option to ask for dynamic memory allocation. So VLAs are the perfect solution. If you don't understand their use, why make bold claims like "nobody uses them"?
@vyacheslavvorobyov22
@vyacheslavvorobyov22 5 ай бұрын
I don't say C must die, but C must not be used in many applications where it is currently used because it is quite dangerous language. For automotive industry, nuclear reactor control, space industry or other real time and critical control systems please use Rust. It is hard to reason about C-written systems, and proove they are correct even in small programs. The Linux Core itself is a strongest proof of how mission critical system written on C, could have a bugs even after of tens of years of development and rigorous testing(by very high qualified C programmers), still showing itself as unexhaustable source of bugs. So, if one develops critical sowtware for automotive industry, aerospace, nuclear reactors control, etc please don't use C/C++ ever, use Rust, if you are worried about your loved ones.
@afnman83
@afnman83 4 ай бұрын
dude, first of all you are confusing bugs of software with the safety features of a language. They are unrelated. Second, In Rust, you can have logical bugs , termination failures, memory leaks, backed by hundreds of unsafe segments of code. Sure its more safe than C, but still there is possibility of that failure. For over 30 years, C/ C++ is everywhere... your OS , your router, is the backbone of everything you are using...
@anon_y_mousse
@anon_y_mousse 3 ай бұрын
@@afnman83 It's not so much that it's safer than C, but rather more annoying to use while giving only an illusion of safety and using a worse syntax than even C++.
@justa5code
@justa5code Ай бұрын
Weird people of C++ community somehow flowed into the world of C and bring this mess. Long Live C17!
@yooyo3d
@yooyo3d 5 ай бұрын
auto should be banned. It's the worst thing added to a language. They can use keyword var like in C#. Anyway, I'm not going to use it in C nor C++.
@afar5y
@afar5y 3 ай бұрын
simply do this: #define var auto
@anon_y_mousse
@anon_y_mousse 3 ай бұрын
Weird, but in this case you could just #define var auto. I might try that approach myself to use constexpr because they should've just changed the behavior of const.
@embeddor3023
@embeddor3023 9 ай бұрын
I hope the next standard will just depricate this bs and force users to switch to C++.
@tommyliu7020
@tommyliu7020 5 ай бұрын
Why?
@JohnJTraston
@JohnJTraston 5 ай бұрын
99% of these features are useless.
@roadrunner3563
@roadrunner3563 10 ай бұрын
Ewww, C was always horrible :(
@ryonagana
@ryonagana 5 ай бұрын
lemme guess rust programmer?
@soniablanche5672
@soniablanche5672 3 ай бұрын
It's literally the simplest language, how is it horrible ?
@VioletGiraffe
@VioletGiraffe 9 ай бұрын
Someone tell these guys C++ exists. And we invented the Internet, too, where you can learn it and other new modern stuff.
@homelessrobot
@homelessrobot 6 ай бұрын
we all know c++ exists. We just rather it didn't
INO IS A KIND ALIEN😂
00:45
INO
Рет қаралды 16 МЛН
Суд над Бишимбаевым. 2 мая | ОНЛАЙН
7:14:30
AKIpress news
Рет қаралды 644 М.
Nonomen funny video😂😂😂 #magic
00:27
Nonomen ノノメン
Рет қаралды 15 МЛН
My Own 3b1b Animation Engine but in C
2:06:44
Tsoding Daily
Рет қаралды 22 М.
Delivering Safe C++ - Bjarne Stroustrup - CppCon 2023
1:29:16
Why I Like Programming in C.
3:16
Francisco Jinto Fox
Рет қаралды 7 М.
How does an OS boot? //Source Dive// 001
50:22
Low Byte Productions
Рет қаралды 359 М.
So You Think You Know Git - FOSDEM 2024
47:00
GitButler
Рет қаралды 888 М.
New Algorithms in C++23 - Conor Hoekstra - C++ on Sea 2023
1:25:20
2 Years Of Learning C | Prime Reacts
22:24
ThePrimeTime
Рет қаралды 224 М.
What's new and what's changed in C23 - Jarosław Stańczyk - code::dive 2023
35:56
Why i think C++ is better than rust
32:48
ThePrimeTime
Рет қаралды 254 М.
Faster than Rust and C++: the PERFECT hash table
33:52
strager
Рет қаралды 492 М.
Phone charger explosion
0:43
_vector_
Рет қаралды 35 МЛН
The PA042 SAMSUNG S24 Ultra phone cage turns your phone into a pro camera!
0:24