lainchan / λ

C General

Lanktik Sparraw · 2020-07-23 05:46
This thread is about all things C. Post all docs and your favorite C repos. What do like about C over other languages?
Haruyoshi · 2020-07-23 23:19
>>19673 Obligatory Suckless and 9front mention. Very simple and hackable. And I like how 9front seems to get away from both autisms of the leftists and 4chanweebs by having edgy things inside of the OS to keep out the leftists and blm/antinazi stuff to keep the chanwackies out. Definitely clever, or maybe Im just overthinking their satire.
null · 2020-07-24 06:16
I don't like how C is considered low level, anything with types isn't low level.
Junichi Fujiwara · 2020-07-24 07:13
>>19685 C barely has types though.
藤原純一 · 2020-07-24 13:27
>>19685 It certainly doesn't have a type system as one ould naturally expect from a typed language. There types are just compiler checks on what is essentially considered memory locations and wordsize differences by any competent C programmer. Question: what is the range of an integer (or a long int) in C?
bit · 2020-07-24 13:41
>>19688 Sounds like any other typed language
Boole · 2020-07-24 14:28
>>19683 Why would I be intrested in 9p as a C programmer ? Is it just simple to read software? I have been reading OpenBSD source code, and found it simple to read.
SuleimanTheDestroyer · 2020-07-24 19:02
>>19685 It's considered a mid-level language. At least in here it is. That's what they say in intro to algorithms l but i heard some countries teach python as their intro to algorithms and heard Computer science and computer engineering has differences. Who would think python as a first language is a good idea? It's easy for the human but hard for the machine. So instead of the human trying to understand the machine and learn it, the machine has to rise up a level. Bad for students. And you can't explain certain fundementals of CE from it. Love the hardware, love the machine lain. Don't hesitate to get down on it's level.
Junichi Fujiwara · 2020-07-24 19:44
>>19689 >Sounds like any other typed language Some languages have dynamic typing, such that a variable can take values of any type. Some have their procedures allow only for a specific datatype, while others have more versatile functions taking whatever datatype you pass to them. Some languages implement a complex typesystem with metatypes that allow for a rich hierarchy of datatypes, and yet others implement them as merely classes of a very general object system. In some languages callable functions are a datatype of their own, others they are a subset of the type hierarchy, while in others they're just a usage of the pointer/reference type. And no language except machine language (and by extension assembly) actually lacks types as far as I am aware. So do explain to me, what do you mean by 'any other typed language' and what language besides assembly counts at low-level then? Anywway the spectrum of low/high level depends of course on the intended usage. Otherwise from the very definition of C being compiled, ie not bearing 1-1 correspondence with machine code, there's no question it being 'high level'. On the other hand for a python programmer it certainly counts as a low level language, or for someone choosing between a shell script or a C program to do a somewhat simple job, say, extracting the 5th column on some input of data.
Debbie Charteris · 2020-07-24 19:58
>>19700 True, you could probably argue that assembly is "high level" if types are the only qualification. It has them in roughly the same sense as C, they just aren't checked by the compiler. After all, the type keywords in C are essentially just annotations for which instruction to use for mathematical operations and such. If you put explicit casts everywhere you'd basically be writing shorthand assembly (setting aside optimization for the moment).
progn · 2020-07-24 23:38
>>19685 I agree. I can go into a chatroom for assembler language and people are only discussing C. The real low-level thread is here: >>43 >>19696 >Who would think python as a first language is a good idea? I agree it's not good, but it's better than other options, so asking the question tries to frame the situation in a way I'd disagree with. >It's easy for the human but hard for the machine. So instead of the human trying to understand the machine and learn it, the machine has to rise up a level. This is what the machines exist to do. >Love the hardware, love the machine lain. Don't hesitate to get down on it's level. C is just as bad as Python for learning how a machine works. Instead of one flavor of nonsense layered over, it's a different layer; in some ways it's worse, because no one seriously argues Python teaches how the machine works, but too many people argue this is the case with C. >>19700 >And no language except machine language (and by extension assembly) actually lacks types as far as I am aware. A machine language can have many types, such as floating point numbers and addresses, and there's pedantry around lacking typing and having but one type. Forth is a wide language which is similar in its lack of typing. >>19701 >True, you could probably argue that assembly is "high level" if types are the only qualification. That would be nonsense. Any machine code is low-level, because it's the bottom level accessible to the programmer. >It has them in roughly the same sense as C, they just aren't checked by the compiler. After all, the type keywords in C are essentially just annotations for which instruction to use for mathematical operations and such. If you put explicit casts everywhere you'd basically be writing shorthand assembly (setting aside optimization for the moment). It really bothers me when people compare C to the machine code like this. This is utter nonsense. If C is so close to the machine, why are the only two compilers people actually use millions of lines of code? A Forth implementation someone would seriously use is simple. An assembler is simple. A C compiler isn't simple at all. The generated machine code is unpredictable and the C standard, which people love to ignore except when they don't, means the two compilers people actually use can and will make assumptions and spit out code which does the opposite of what the programmer asked for, in some cases.
Milner · 2020-07-25 03:52
>>19683 >cant go more than 3 nanoseconds without bringing up politics YOU HAVE TO GO BACK suckless is soykaf (but less soykaf than gnomecrap, obviously) plan9 9front 9this that9 go are actual garbage and the hipster of the neckbeard world >>19696 >Who would think python as a first language is a good idea? can't be as bad as C as a first language >"""fundamentals""" C elitism is mostly kids with no idea what they're talking about who think they are now experts on da machine and above all da fake webshotters because they ran a linker and made a cache coherent algo. their learning typically stops there and they go on 15 years creating braindamaged crap full of trivial stack smashing problems, with nobody to criticize them. 30 years later some bored infosec bro disassembles their code and has a laugh The C elitist club is no different than a little forum like macrumors or Tom's Hardware. Nothing but mindless consumers repeating the same 3 stupid justifications why their brand is better. C is a terrible language even for low level code. Not a single thing is done correctly, as that would require convincing a Ctard that he was wrong about something. Even the syntax is orders of magnitude worse than absolutely any other mainstream language, even Erlang.
Tyrell Wellick · 2020-07-25 04:53
>>19705 C is fine. It's orders of magnitude better than any of the languages that evolved from it (Objective-C, C++, C#) and it's more modular and readable than typical assembler. Perfectly fine language when written correctly.
Humean · 2020-07-25 07:01
brainfuck is a fine language when written correctly
Jens Hansen · 2020-07-25 09:35
>>19685 the possibility of types in c doesn't equate to java level abstraction, for instance. it literally is just a block of bytes with a label associated to. it. I would call it a compiler DLC, for the sake of humans generating code
Mario Rossi · 2020-07-25 10:06
>>19709 I would argue with that as brainfuck was made with the intent of making a turing complete language with a smallest possible compiler. It never been made with the intent of solving any real live problem. C on the other hand was created with the intent of making a language that allows writing portable code.
kale · 2020-07-25 13:13
>>19673 so guys i got the c programming book second edition, and trying to learn C, any tips for me?
Motoko Kusanagi · 2020-07-25 15:41
>>19715 Make sure you understand pointers .
x<->y · 2020-07-25 15:56
>>19703 I didn't say C was particularly close to assembly language, I said C doesn't have much stronger typing than assembly, although I'll admit the concept of what constitutes typing gets kind of muddled at that point and it probably wasn't the best example on my part.
Pulse · 2020-07-25 17:08
>>19718 A C compiler like GCC will enforce typing in some ways the typical machine code won't, through exploiting undefined behaviour. >I'll admit the concept of what constitutes typing gets kind of muddled at that point We agree there. A machine code can have typing, a simple way through hardware tagging. The machine can enforce this by requiring that, say, addresses have the address tag, and then restricting the ability to modify tags, which don't even need to be in contiguous memory with the tagged objects. Most machine codes aren't like this, but it's important to be aware that there's nothing stopping such, and some machines have featured such and more.
H.R. Giger · 2020-07-25 17:53
>>19720 >A C compiler like GCC will enforce typing in some ways the typical machine code won't Fair enough >Most machine codes aren't like this This is probably exposing the limits of my knowledge when it comes to the theory of programming languages, but couldn't the way machine instructions treat e.g. floating point numbers be considered rudimentary typing? Your instruction choice tells the CPU "this register is to be treated as a float and handled by the float arithmetic system". Sure, it's highly mutable but types in C are mutable in a very similar way, for instance you can declare "the memory referenced by this symbol will no longer be handled using floating point instructions" by explicitly casting it to an int. Genuinely curious about how you would draw this distinction.
Fred Nurk · 2020-07-25 17:55
>>19721 I'll add that I think my initial couple posts were conflating weak typing with nonexistent typing, I just don't have a clear conceptualization of what constitutes "not having a type system".
Dox · 2020-07-25 18:03
What about it?
Chani · 2020-07-25 18:11
>>19717 Also don't be scared of them. Can't tell you how many people I've seen fail just because someone told them pointers are hard. Kind of like math, but even easier. Bonus points if you get into assembly as well, no way you don't end up understanding pointers. Also, when you start getting into dynamic memory allocation, make a habit of using valgrind. It helps pointing out a lot of rookie mistakes, at the very least.
Marly Krushkhova · 2020-07-25 19:05
>>19723 hahaha
Lain Iwakura · 2020-07-25 20:42
>>19703 >It really bothers me when people compare C to the machine code like this Because these words come mostly from retards that didn't touch the subject any deeper than "Hello world!". It's their excuse for not touching it any further and sticking to their C++.
pop · 2020-07-25 21:06
>>19721 But that floating point can be treated as a chars in assembly, you don't need to cast it like you would in C.
FILLER · 2020-07-26 00:29
>>19721 >This is probably exposing the limits of my knowledge when it comes to the theory of programming languages, but couldn't the way machine instructions treat e.g. floating point numbers be considered rudimentary typing? Yes, which is why I pointed it out the way I did. As for C, there's undefined behaviour in type coercion, which is part of the issue. An assembler is broken if it removes a security check, but C compilers can and do in the name of undefined behaviour. >>19722 Again, it's largely without much distinction. Someone who doesn't like type theory will look at a language like Forth and call it typeless, where each operation expects certain characteristics, whereas someone who does like type theory will call it a degenerate case of singular typing or whatever.
protected · 2020-07-26 03:20
>>19730 An assembler that does security checks is not an assembler, it's a compiler, an assembler should not be able to make decisions for the programmer, it should be assumed that the programmer knows what he is doing for it to be a low level language.
hash table · 2020-07-26 03:40
>>19730 assemblers do security checks? I thought all they did was check that the code assembles
quote · 2020-07-26 05:48
>>19732 >>19733 I'll rephrase: An assembler is broken if it removes a security check the programmer wrote, such as checking if a pointer is valid before using it, but C compilers can and do remove such checks the programmer wrote out from under him, in the name of undefined behaviour.
Turner · 2020-07-26 07:31
>>19734 ya ok
Spike Spiegel · 2020-07-26 08:35
>>19734 in what way? I've never heard of a C compiler being allowed to simply remove or modify program logic.
FILLER · 2020-07-26 15:25
>>19739 Read this page, and its two siblings: http://blog.llvm.org/2011/05/what-every-c-programmer-should-know_14.html In particular, pay attention to the contains_null_check_after_RNCE_and_DCE example; this actually affected a null check in the Linux kernel in a similar way, completely removing it. I can't locate the news article detailing that Linux kernel bug itself, currently.
Splicer · 2020-07-26 16:48
>>19739 Optimization options can also do that. Think gcc -o2.
Boris Grishenko · 2020-07-26 16:49
>>19742 *-O2
hash table · 2020-07-27 03:06
So, i have some basic notion of C (modern approach level), and was interested to learn more advanced stuff like low level, networking, etc.Which book/resource do you guys recommend?
DEBUG-CONTENTS · 2020-07-27 03:23
>>19747 Check out "Expert C Programming: Deep C Secrets" by Peter van der Linden. He does an exceptional job of bridging the gap between high/low-level thought processes.
typedef · 2020-07-27 14:04
>>19749 Nice, it seems to have a lot of stories about the Utnix and C as a whole.
Lukasiewicz · 2020-08-02 12:34
I would like your thoughts on this guys tips https://www.youtube.com/watch?v=443UNeGrFoM
progn · 2020-08-02 13:30
>>19829 overall good video
Kay · 2020-08-02 18:09
>>19829 Judging from the video's thumbnail, I can already tell this guy is foolish with his function overloading example. If you add two differing numeric types, whether by a function or build-in operator, then you, the programmer, should be aware of the rules that govern such an action. I'd also like to take this moment to remind everybody that templates > overloading. d T add(T)(T a, T b) if (isNumeric!T) { return a + b; }
Haruyoshi · 2020-08-02 21:42
>>19834 Don't judge by the thumbnail, this guy is a highly competent programmer.
Spooky · 2020-08-03 04:28
>>19842 Well, I disagree with his opinion on operator overloading (and overloading in general). His example with vectors illustrates two problems, neither of them being the one he stated: the person who designed the struct/class made a poor decision, and he's too lazy to read the docs of the code he's using. I've seem some stupid examples in C++ with overloaded operators being attached to weird operations, but taking away 'advanced' features away from all programmers because there are those who make bad design choices is stupid. It's like throwing C out the window because it allows programmers to easily corrupt memory.
let · 2020-08-03 17:27
>19688 >Question: what is the range of an integer (or a long int) in C? Depends on the CPU architecture. For x86/amd64 Int = 4 bytes (max 2^32 unsigned) Long int = 8 bytes (max 2^64 unsigned)
Nobody special · 2020-08-03 17:28
>>19876 >>19688 I'm a fool, missed the second > bracket.
Wirth · 2020-08-03 22:17
>>19876 More like [0, (2^32) -1] for unsigned int [0, (2^64) -1] for unsigned long int But yes > Does this still look automated? > Holy crap it does > Am I even human?
Marly Krushkhova · 2020-08-03 23:01
>>19889 The size of int and long int are subject to the data model. The only reliable way to get 64-bits is a long long int. https://en.wikipedia.org/wiki/64-bit_computing#64-bit_data_models
Hong, Guil Dong · 2020-08-04 01:35
>>19891 What about C99 inttypes.h ?
John Doe · 2020-08-07 01:19
Is there any sane way to build a C program for Windows other than using MinGW? I have a program I'm writing for Linux/BSD, and I've decided to use cross-platform libraries so that it _should_ be able to run on Windows as long as I can replace the a few minor POSIX-reliant parts. But it seems like Windows is hostile to developing software without some clunky IDE and integrated build system. I've heard of nmake, and Windows does have a compiler that runs in the shell, but I haven't seen any software that uses such a system, or any material online about how to make a Windows program using such a system. I'm also not familiar with how linking and DLLs work on Windows, and that might be part of the reason that people don't write C programs for Windows, but I would hope it's similar enough to how it works in the Unix realm. Does anyone have any material or information that might help me out?
Frank Garza · 2020-08-07 07:15
>>19691 A really good way to learn C is also to read FreeBSD source code
nil · 2020-08-07 18:20
>>20044 MSYS2
aliased · 2020-08-08 00:44
I'm looking to learn C. Many have said that the way to go with learning it is to read K&R, but I'm kind of having a hard time wrapping my head around the wording, Like I have to re read the same paragraph many times over until I see what it's trying to say. Is there a better way to learn or should I just stick with the book?
sizeof · 2020-08-08 01:05
>>20085 someone posted some heads first C book in one of the threads, I am reading through it slowly, but I like it so far, but the best way to learn anything is by practice.
Boole · 2020-08-08 11:41
>>20085 Learn C the Hard Way by Zed Shaw
nibble · 2020-08-08 14:50
>>20104 fuarrrk Zed Shaw, he's a complete tool who once claimed Python3 wasn't Turing complete.
Lady Jessica · 2020-08-08 19:34
>>20109 I thought to add an "inb4 someone complains about Zed Shaw" but I hoped this place was better than that. I guess it's true. Lainchan is barely better than /g/ anymore. RIP.
Acid Burn · 2020-08-10 16:29
>>20085 watch this guy's c videos https://www.youtube.com/channel/UC6qj_bPq6tQ6hLwOBpBQ42Q/videos just don't copy his habit of using microsoft-specific "_s" safe functions (ex. fscanf_s) be careful of these c standard library functions that deal with strings, memory manipulation, input/output https://github.com/intel/safestringlib/wiki/SDL-List-of-derezzed-Functions never use scanf (with fgets you have to do the extra step of making a string buffer), don't bother with 3rd-party "safe" functions, banning memcpy and memset is a little extreme since lots of projects including linux kernel still use them but be aware of how buffer overflow attacks work on them read chapter 3 of Expert C Programming - Deep C Secrets (1994) ( https://libgen.is/book/index.php?md5=A37157F0C0DD95A3BC304B4AD5E9EB30 ) to understand why char* const *(*next)(); is read "next is a pointer to a function returning a pointer to a const pointer-to-char" follow the linux kernel c programming style guide https://www.kernel.org/doc/html/v4.10/process/coding-style.html if you're on windows make sure you know how to install mingw and run gcc from cmd, learn about the common gcc compiler flags when compiling such as -O2 (see how it effects output filesize, performance, etc.), -Wpedantic and Wdeclaration-after-statement to ensure ANSI/C89 compatibility
Anamika · 2020-08-10 23:43
>>19724 I've never met a single programmer who could explain pointers beyond "hurr it points" which is horrible for a beginner.
array · 2020-08-11 00:17
>>20169 A pointer is an address in memory.
Turing · 2020-08-11 00:18
>>20169 What would you suggest? I'm reading head first C (someone posted it) I think it explains pretty well.
Backus · 2020-08-11 00:36
>>20169 Beginners should first understand the difference between call by value or by reference and then pointers.
Jim Hilger · 2020-08-11 14:26
>>20126 >anyone who disagrees with me is a /g/ pleb
Apoc · 2020-08-11 14:45
>>20174 Technically everything is by value in C tho. It's just that some of those values happen to be memory addresses. From my understanding C++ pass by reference actually handles this differently but idk enough about C++ to explain it.
Armitage · 2020-08-11 16:55
>>20109 >who once claimed Python3 wasn't Turing complete. The Python developers said, "Python3 *can't* support Python2.", so Zed Shaw said "Wow really? I guess that means Python3 isn't Turing complete."
Unknown · 2020-08-12 23:38
>>20174 I think so too. I believe that's how K&R handles it. It's more useful to know what passing by reference/value means.
Bobby Newmark · 2020-08-13 01:11
>>19685 Every instruction set architecture specify types and split the instruction concerning the type which is being considered, so this definition is not a good one to consider something low/high level.
pop · 2020-08-13 08:00
>>20210 That's not accurate. The x86 CPUs infer the bit width from the register being used.
nil · 2020-08-13 15:44
>>20211 It is not a inference its well defined in all implementations of x86 family, the register being used is encoded in the instruction and the instruction specify a type.
if · 2020-08-13 15:59
>>20211 >Example 1 https://www.amd.com/system/files/TechDocs/24592.pdf#G9.1485675 As a simple example notice how AMD manual defines the "Untyped data objects" under the Fundamental Data Types section. >Example 2 https://software.intel.com/content/dam/develop/public/us/en/documents/325462-sdm-vol-1-2abcd-3abcd.pdf#G6.2150 Intel manual gives us an entire chapter just about data types and it not exhaust all the types because of all the extensions we have acctually.
Lady Jessica · 2020-08-15 23:38
You do embedded anons?
Masami Eiri · 2020-08-16 01:30
>>20085 Quitters never win and winners never quit. If a strategic retreat is neccessary then so be it.
Mentat · 2020-08-16 01:48
>>20085 If this is your first time trying to learn programming seriously, know that K&R was written for people who were already comfortable with other languages
let · 2020-08-16 03:27
I like C because I can, simply, tell the computer to do things. Aside from the fact that parts of the standard library are awful and the toolchain is convoluted, the simple idea of "tell the computer to do things" makes it my favorite language.
Cowboy · 2020-08-16 07:46
>>20296 > I can, simply, tell the computer to do things. I'm not sure what you wanted to say here, but all languages work in a way " tell the computer to do things."
Wintermute · 2020-08-16 16:50
>>20297 With higher level languages you are more telling the computer what you want it to do, with languages like C a lot of the core parts of it involve actually telling it what to do. Something like C# is extremely abstracted away from what the computer actually does compared to C.
Ivan Petrov · 2020-08-16 19:12
>>20300 What you are really saying is that you prefer C over let's say Python because C is lower level then Python. If you "actually" want to tell the computer what to do then you should pick up assembly as there still is a lot of things hidden from the user in C (like what "actually" happens before the main starts, or what happens when you call some function, what happens when you call malloc and so on...).
Colmerauer · 2020-08-16 20:21
>>20302 Im another anon, but this kind of discussion dont have end, so let me prevent you both to continue until it reach the nonsnse. Even when we are writing assembly we are just letting the microprocessor break down the instruction in micro instructions(uops) and then do what it should do, thus its possible to write code under the level of assembly. Some can say not all processors will use microcode/microprogramming... its true but in all the cases we will have something which implement something to control all the signals to produce the results we want when providing a bunch of instruction to be executed. This can be hardwired... can be microprogrammed we have even some schemes which uses both... in the end it just matters if we are going to design the microprocessor at all. The same approach of thinking leads to a conclusion which is "equals" to the one you provided... but let me put this with my broked english. Discussing if a language is low-level and saying its better because it is is pointless, since we can always go to level which is "more" low-level... we can reach the point of using some Hard description language(HDL), as verilog or anyother to describe the circuits which will "run" the things, but we can still going with the same thinking and reach another level which is not possible to describe with those HDL.. like the kind of transistors, the technology used to build those transistor... and we can keep going.... what of those languages is the better? No one, it always depend on the following question "better for what?". And another useful thing to think about this discussion is that... no matter on what HIGH level you are, you can goes through a chain of FFI and reach the low-level to "say the computer what to do". Some interesting links about the subject: >microcode / microprogramming https://people.cs.clemson.edu/~mark/uprog.html >Foreign Function Interface https://en.wikipedia.org/wiki/Foreign_function_interface https://docs.python.org/3/library/ctypes.html
Jean Dupont · 2020-08-16 21:26
>>20303 yup, at the end of the day it is a matter of which language is best for a particular task. It feels to me like these "which programming language is best" arguments are a lot like carpenters arguing over which kind of hammer is best. Which would never happen because every carpenter knows that you use different hammers for different tasks.
Motoko Kusanagi · 2020-08-16 21:42
>>20303 >not etching a custom ASIC for each program you want to make plebs
Chani · 2020-08-16 22:44
>>20303 Steve Wozniak used to just fire up the apple 2 "monitor" (ram editor) and type in hex codes to do quick and dirty programming.
byte · 2020-08-17 00:12
>>20300 >what the computer actually does C isn't really that much closer to the metal than any other compiled language. It has a memory management system that's kinda sorta like real hardware, but even that's pretty abstracted.
Stallman · 2020-08-17 13:23
After half-assing (more like quarter assing) my C for years decided to use this and finally do it properly, any suggestions???
list · 2020-08-17 13:42
>>20316 try reading it, I guess?
Spooky · 2020-08-18 00:32
>>20316 it's absolute clusterfuck
The Oracle · 2020-08-18 01:00
>>20322 What do you mean? It's not worth it?
John Doe · 2020-08-19 00:12
>>20303 >Even when we are writing assembly we are just letting the microprocessor break down the instruction in micro instructions(uops) and then do what it should do, thus its possible to write code under the level of assembly. This is painful to read. I'm not trying to provoke anyone, but so many C programmers argue C is what the machine really does and is so low-level, and then backtrack when someone points out how wrong that is by just trying to destroy the idea of low-level, rather than concede. This is like when C programmers are expert hardware designers who point out type-checking in hardware will always have some small cost, no matter how infinitesimal, and then ignore searching for null bytes to get string lengths, when arguing about performance. Since it came to mind, here's an example of similar idiocy: https://lord-left.github.io/posts/love-coding-c.html >As I played around with pointers and printed out a memory location, I experienced a literal chill down my spine. I had almost forgotten how marvelous programming in this language was. >When I saw a memory address outputted to stdout, I felt that I was as close to the hardware that I could be without literally opening up my machine and stroking my ram modules like a crazy person. I'd rather take further criticism of C to the thread dedicated to this, than continue here.
McCarthy · 2020-08-19 01:07
>>20358 Why this is painful to read? If you get it right you will know this post agree that C is not low level.
McCarthy · 2020-08-19 14:06
>>20358 >This is painful to read. I'm not trying to provoke anyone, but so many C programmers argue C is what the machine really does and is so low-level, and then backtrack when someone points out how wrong that is by just trying to destroy the idea of low-level, rather than concede. This is like when C programmers are expert hardware designers who point out type-checking in hardware will always have some small cost, no matter how infinitesimal, and then ignore searching for null bytes to get string lengths, when arguing about performance. I'm a C programmer with some embedded experience - and no one was in my work attempting to say such retarded things. Especially after few projects had to patch/workaround issues of C compiler generating errorous or jest counterproductive binary code. Also LOL at the other guy you cited who said "he is as close to hardware as he can get" because he can print mempry address values. Good luck using CPU extensions in pure C w/o using assembler. LMAO
Nemissa · 2020-09-05 20:24
This is a really enjoyable read
Yet Another Lainon · 2020-09-05 22:18
>>20666 the cover looks nice. I wanna read a book on squids
Nobody special · 2020-09-07 19:37
>>20667 That's Cthulhu, quite the bold statement about C >Lovecraft broke with other pulp writers of the time by having his main characters' minds deteriorate when afforded a glimpse of what exists outside their perceived reality. >Human beings, with their limited faculties, can never fully understand this universe, and the cognitive dissonance caused by this revelation leads to insanity, in his view.
Batou · 2020-09-07 23:57
>>20358 come on, I read your link and he is clearly aware of the pros and cons of C > I hope that it is clear that what I am describing is fundamentally a feeling, and is as such highly subjective and is also not morally superior to any other preference. There are a lot of holes in this notion of C being “close to reality.” But it feels that way, and in articulating this, I hope I am able to explain some of the psychological appeal of lower level programming in C. you're cherry picking from this guy
Mentat · 2020-09-11 07:30
>>19705 >suckless and plan9/9front is soykaf I agree >C is a bad first language Couldn't be more wrong. By learning C first you learn how a computer works and you'll be able to pick up other languages much easier, as most of the popular languages are based on C such as Go, Rust, Python, Javascript, etc. It's also very easy to get into, but difficult to master, but all that really means is you won't have a rough start and you'll have plenty of things to learn at your own pace. >muh elitism Oh so you're just butthurt, ok. I'm not a good programmer, but I can at least read code and understand when something is done well. Your arguments boil down to "the majority of C programmers don't know how to write good code in C" which is kind of true, like I said C is difficult to master, but that's not an argument against the language. Your only sort of argument against the language is that the syntax is bad, yet with all those paragraphs you never explain how or why, you just end it because you don't know what you're talking about. It's pretty embarrassing that you're implying even Java has better syntax. You sound like more of an elitist of sorts than anyone else ITT.
John Titor · 2020-09-11 11:36
>>20768 Not the original poster, but. >Couldn't be more wrong. I think that's not wrong - I tried learning C++ as my first language, but the level of inconsistency, unintuitive syntax, non-linear syntax of pointers, etc. made me stop. I picked Scheme instead of C/C++ and I am happy with it. You don't need pointers or manual memory management, etc. in your first programming language - these concepts are not important for a beginner. What is important for a beginner is to get a big picture of what programming is about and to learn how to turn ideas into code, how to make algorithms, etc. >By learning C first you learn how a computer works My friend who knows assembly, told me I won't know how computer really works, If I learn C. Where is this meme from? Do you really know how ALUs, FPUs, registers, etc. work after learning C?
Jean Dupont · 2020-09-11 12:28
>>20768 >Couldn't be more wrong. By learning C first you learn how a computer works and you'll be able to pick up other languages much easier, as most of the popular languages are based on C such as Go, Rust, Python, Javascript, etc. Go, Rust, Python, sure - especially Go. But Javascript is its own weird beast. The syntax kinda-sorta looks C-ish at first glance, but in practice it's totally alien to the C family.
vector · 2020-09-11 23:50
>>20768 >By learning C first you learn how a computer works If you're talking about "machines that run programs and perform calculations" in general, Basically any turing-complete language could teach you that. If you're just referring to von Neumann machines and related architectures (which I'm 99.999999999999% sure you are), kinda sorta but not really. C has manual memory management, sure, but the way you think of memory while writing C is very different from the way you think of it while writing assembly.
Ein · 2020-09-12 17:38
>>20769 >Do you really know how ALUs, FPUs, registers, etc. work after learning C? In a sense yes because those things can affect your C code in ways they won't affect a high level managed language. Not that you magically know these things after flipping the last page of k&r but if you write C long enough and seriously enough then you will have to gain a good understanding of what's going on in lower levels out of necessity. >My friend who knows assembly, told me I won't know how computer really works, If I learn C. And assembly is just another high level language which the CPU converts into microcode. You can make the same argument all the way down the stack. What >>20769 probably means is that you'll learn more about how computers work through C than higher level languages which try to hide all the gory details from you.
Frank Garza · 2020-09-13 16:20
>>19705 >suckless is soykaf What don't you like about it? Or do you mostly just think it's overrated? I'm not a suckless zealot, and I think their way of doing things works better in some use cases/applications (dmenu, sxiv) than others (dwm), but I do think their code is very well written and I've learned quite a bit from reading through it. The general philosophy is also interesting enough and at least gets the desired results (simple software that is extremely versatile and easy to fork) if nothing else. My main problem with some of their projects, dwm in particular (and to a lesser extent st), is that the patch management thing doesn't scale well to more complex software. This isn't even some innate problem with patches vs. runtime plugins, so much as a conflict with their other principles. If they really wanted a minimal feature set that's extensible with patches, they should have written the code in a more modular way, so that entire modules can be replaced by the user rather than a bunch of small changes throughout the source code. That way you aren't dealing with merge conflicts all the time. However, abstraction like this is "suck" in the sense that it makes the code more complicated than is strictly necessary for the functionality of the program, which means it is more difficult and error-prone to maintain, so they don't do it. It's interesting to compare dwm with something like xmonad or bspwm, because they're all kind of just different takes on what a wm motivated by the Unix philosophy should look like. Dwm opts to simplify the role of the wm as much as possible and tries to make the codebase small and straightforward. However this means the codebase itself relies on a lot of really long methods and minimal abstraction. Xmonad's codebase is much more complicated (full disclosure: I'm not much of a Haskell programmer and haven't spent much time with xmonad), but the Unix philosophy is applied at a more granular level. Since you're intended to hack around with xmonad on the fly most of the functions are short and "do one thing (within the window manager) well". So extending xmonad is a lot like writing Unix-style shell scripts. I don't know much about bspwm but from my understanding rather than extending it through patches or internal runtime configuration, it just has a very flexible RPC api which is easy to control/integrate with shell scripts.
Y.T · 2020-09-13 19:12
>>20798 Not >>19705 suckless is bad because it snubs its nose at complexity while simultaneously tying itself to the baroque mess known as Unix. They forget that much of the complexity in software comes from trying to support existing software and then snub their nose at things like GNU. GNU software is some of the most robust, portable, and documented software available. This was not easy. They tie themselves to the worst parts of Unix. For example, they love the edit, compile, run cycle so much that they avoid the use of configuration files, "Why use a configuration file when you can just recompile and rerun?" This is old and dumb. Since the 70s, it's been possible to redefine arbitrary functions during runtime. I'm not saying configuration files are a great things, but they're a lot better than having to restart a program because the system software can't handle live updates. My two cents.
Haruyoshi · 2020-09-14 01:27
>>20783 > you'll learn more about how computers work The goalposts have moved, how convenient.
() · 2020-09-14 06:04
>>19747 I thoroughly enjoyed 21st Century C, though there are several chapters you can skip if they are not relevant to you (source control, etc..)
string · 2020-09-14 08:34
>>20805 >the baroque mess known as Unix. Stopped reading there. :3
Ein · 2020-09-14 12:36
>>20810 >The goalposts have moved, how convenient. Imagine thinking you're never allowed to update your opinions as more knowledge becomes available. >>20805 >tying itself to the baroque mess known as Unix. Just because the platform is complex and evolved in awkward ways doesn't invalid someone's effort to build something minimal on top of it. This sounds like nirvana fallacy. What would be the alternative, anyway? >[suckless] snub their nose at things like GNU That's because they value simplicity and GNU is pretty much the opposite of that in every way. https://web.archive.org/web/20150519100236/https://gist.github.com/dchest/1091803 >They tie themselves to the worst parts of Unix. For example, they love the edit, compile, run cycle so much that they avoid the use of configuration files, I don't understand what this has to do with Unix. Suckless is about simplicity and there's nothing simple about parsing a semi-natural language configuration file and then keeping all the options consistent and backwards compatible across software versions. >Since the 70s, it's been possible to redefine arbitrary functions during runtime. Again, how much code and complexity actually goes into that? You essentially need to bundle a whole language interpreter with your program to do that. >My two cents. Well yeah, nothing you've said is an objective criticism. You just value convenience more than simple code and suckless is the opposite.
array · 2020-09-14 13:20
>>20810 >The goalposts have moved, how convenient. Moving the goalposts is when someone shows you evidence and you say it's not good enough and keep asking for "better" evidence. When someone makes a dubious claim and when challenged switches to a lesser, uncontroversial claim that's called motte and bailey. But in this case it's obviously two different people making two different claims so that doesn't apply either.
overriding · 2020-09-14 16:04
>>20827 >What would be the alternative, anyway? Instead of writing command line programs that look like function calls with getopt style argument parsing just use functions. >Again, how much code and complexity actually goes into that? You essentially need to bundle a whole language interpreter with your program to do that. It would take less code and complexity than what already exists. We already *have* this system on Unix, but the way it's defined is moronic. Instead of functions with function signatures, there are programs that accept a list of argument strings and have to parse them manually. Instead of dynamic linking of functions, programs are looked up as files through PATH. (And they say dynamic linking is slow!) Instead of arbitrary function redefinition, only functions that correspond to an entire program file can be redefined without restarting a subsystem. Instead of function return values, programs communicate in byte streams. The whole system is desperately trying to implement what I've described, but it does it in an ass backwards way. Command line programs are a poor man's functions. >Suckless is about simplicity and there's nothing simple about parsing a semi-natural language configuration file and then keeping all the options consistent and backwards compatible across software versions. You don't need new parsers if you stop making up new syntax. JSON is fine. The parser is not a problem and hasn't been for a long time. Maintaining backwards compatibility and consistent options is just a matter of good software development. If the developers can't maintain consistent configuration options, what makes you think your patches have any chance of working next time you upgrade? >>20827 >You just value convenience more than simple code and suckless is the opposite. There are simple implementations and there are simple interfaces. Suckless is the former. This is known as the New Jersey approach. http://dreamsongs.com/RiseOfWorseIsBetter.html
↑ · 2020-09-15 19:40
>>20817 >Stopped reading there. :3 I guess it's written by a baroque mesy individual lurking at #programming and praising lisp as God's true programming language. Oh yeas, the Language that brough us clean and pure minimalistic EMACS Operating System.
Hiro Protagonist · 2020-09-15 20:36
>>20855 >I guess it's written by a baroque mesy individual lurking at #programming and praising lisp as God's true programming language. Don't mix Lisp into it. The fallacous thinking of the lain you're replying to has nothing to do with Lisp. Also discussing UNIX is out of the scope of this thread, if you want discuss that, make a new thread.
bit · 2020-09-15 20:37
>>20855 > Oh yeas, the Language that brough us clean and pure minimalistic EMACS Operating System. This but unironically.
Splicer · 2020-09-16 01:28
>>20835 >Json is fine That's just like your opinion man
Meddler · 2020-09-18 00:30
>>20855 I don't get why Lisp vs C is a thing. They're so different at such a fundamental level that it's worthless to compare them. It'd be akin to saying Haskell is better than Java, or that C++ is better than Perl.
Tank · 2020-09-18 17:29
>>20894 Because they are from the same era, C won, even though it was worse at the time.
BloodCat · 2020-10-09 13:44
>>20859 >The fallacous thinking Saying "fallacous" when you mean stupid doesn't make your words suddenly carry weight. >>20866 JSON has an ISO standard less than 30 pages long and supports all the syntax needed to replace ad hoc Unix formats and almost all XML and YAML usage. Please don't pretend JSON's minuscule well defined standard is too much to implement. Please don't pretend that JSON is somehow insufficient for something like /etc/passwd. The structure of Unix configuration files clearly revolves around how strtok can be abused rather than any conscious design decisions.
Hiro Protagonist · 2020-10-09 15:49
>>21221 >JSON has an ISO standard less than 30 pages long and supports all the syntax needed to replace ad hoc Unix formats and almost all XML and YAML usage. I never really groked the whole "XML hatred" thing until I actually tried to use it (as part of an XMPP-using project - trying to do 2FA over PGP-encrypted XMPP). Complete soykafshow. I would love a hypothetical XMPP-but-using-JSON protocol. Not just some XEP, but a standalone alternative that jettison XML completely and relies solely on JSON.
Koichiro · 2020-10-11 20:21
>>21221 JSON's better than XML, but S-expressions are better than either.
Davis · 2020-10-12 00:21
>>21221 >Saying "fallacous" when you mean stupid doesn't make your words suddenly carry weight. Except that's the right word for the context. They clearly meant that the thinking is pivoted on a fallacy, and thus is fallacious. Your post reeks of bad faith.
Void · 2020-10-12 21:33
>>21316 Nope. Bad faith is calling something "fallacous" without pointing out a single fallacy. You and >>21316 think name calling like "fallacous" is a sufficient response. No fallacies were given. (Probably because there are none present.) You didn't provide any substance or argument. Nothing accompanies the name calling; it's just a baseless insult. It doesn't matter if >>21316 is sitting on a book worth of fallacies in the argument because he didn't provide any.
Colmerauer · 2020-10-13 13:47
>>21309 The main benefit of JSON is that there's already an ISO standard. I'm aware of no comparable s-expression standard. This is important, because tools made to alter one s-expression file should work on all of them. ; Does your standard support this? #.(+ 2 2) I guess there's this: http://people.csail.mit.edu/rivest/Sexp.txt
progn · 2020-10-14 17:21
>>21378 You could use the basic scheme datastructures which are standardized, as most other Lisps support them just fine. There is also s-exp which >>21378 mentioned.
aliased · 2020-10-20 05:47
Is there a specific reason C doesn't have a built-in string data type or is there any reason not to include one?
t · 2020-10-20 11:23
so i decided to try learning c by doing/(fuarrrking up) a project. i was thinking of making a program that would make desktop notifications when a thread on here updates. i don't want to get burnt out relearning everything i already learned from other languages so can anyone help point me to a library/api/... that i could use to mess around with html.
Lain Iwakura · 2020-10-20 11:58
Optimization noob here. I was reading Abrash's Black Book and he puts a heavy focus on Assembly Language Optimization, but given how outdated the book is is Assembly Optimization still relevant for making code faster?
Random · 2020-10-20 16:46
>>21515 I would assume it's because the model it uses is a stream of characters.
Cereal Killer · 2020-10-20 23:48
I'm writing some C and have run into trouble, maybe somewhere here can give me some direction. I've been doing the cryptopals challenges and am about to complete the first set, all that's left is to write an implementation of the ECB mode of AES. One component of AES is a particular function, or LUT, called the S-box. I read about that and found this snippet which initializes the table: <code> #include <stdint.h> #define ROTL8(x,shift) ((uint8_t) ((x) << (shift)) | ((x) >> (8 - (shift)))) void initialize_aes_sbox(uint8_t sbox[256]) { uint8_t p = 1, q = 1; /* loop invariant: p * q == 1 in the Galois field */ do { /* multiply p by 3 */ p = p ^ (p << 1) ^ (p & 0x80 ? 0x1B : 0); /* divide q by 3 (equals multiplication by 0xf6) */ q ^= q << 1; q ^= q << 2; q ^= q << 4; q ^= q & 0x80 ? 0x09 : 0; /* compute the affine transformation */ uint8_t xformed = q ^ ROTL8(q, 1) ^ ROTL8(q, 2) ^ ROTL8(q, 3) ^ ROTL8(q, 4); sbox[p] = xformed ^ 0x63; } while (p != 1); /* 0 is a special case since it has no inverse */ sbox[0] = 0x63; } <code> Now my issue: this code does not produce the desired output. I knew portability was an issue with C, but fuarrrk, what could be going wrong?
string · 2020-10-21 14:09
>>19723 >Not to be confused with the HolyC created by the devil himself in order to burn the world itself wtf
Delilah · 2020-10-21 16:11
>>2153 What is the expected behavior, and what is it doing instead? At a glance, you may want to make sure uint8_t sbox[256] is doing what you expect it to do. That's a somewhat unconventional syntax for taking a pointer to an array as an argument, so I can't tell if it's a mistake or C wizard soykaf. Afaik specifying the size doesn't actually do anything, so as a function argument its the same as uint8_t *sbox. Meaning you should be passing a pointer to your array and ensuring that the lifetime of the array (particularly if it's stack allocated) is correct in the calling function. As for implementation specific things, I'd run through your code in a debugger and make sure all those shifts are doing what you expect them to, and that you're actually getting 8 bit integers everywhere. Or just throw in some assert() statements after each step.
Switch · 2020-10-21 16:37
So in compiled C, how do functions work? all functions in C are actually pointers to the address of functions. So what happens when you call a function? It compiles to an unconditional jump to the code? When you call a function, where are the parameters copied to so the function can use them? Different locations for different functions or different call of the function?
Cat Mother · 2020-10-21 17:04
>>21543 Look up "C calling convention". This is a deeper issue than can easily be explained in a post, but essentially the thing that makes a function call different from an unconditional jump (aka a goto) is that your CPU has to store arguments in specific registers so that the function knows where to look for them, has to put the return value in a specific register so that the calling function knows where to look for it, and also has to save the values of certain registers to memory so that they can be restored when the function returns. There's more to it than just that (what do you do with arrays or other large stack-allocated data structures? what is the difference between static and external functions? how does inlining work? how does tail-call recursion work? how do you handle functions from external libraries? what is the difference between a static and dynamic library? how do function pointers work? what makes class methods in C++ different from C functions? what about closures and lambdas in other languages?) but that's the basic idea.
Agent Smith · 2020-10-21 20:16
>>21538 I know next to nothing about cryptography, what is all that? https://www.samiam.org/galois.html https://www.quora.com/How-is-an-S-box-constructed-in-AES https://captanu.wordpress.com/2015/04/25/aes/ (nice pictures) Oh, okay... Are you sure << has a higher precidence than ^= ? (apparently it does, please use parenthesis anyways) Your code rotates bits but the "rotates" on the page I found are simple shifts (with possible ^= 0x1b after). I'm mixing up multiplying with taking an inverse... Nevermind me! It would be easier to: // using lut[0] = 0 static const uint_8 LUT[] = { 0, 0x63, 0x7c, /* etc... */ And just copy the values from somewhere, with double-check testing, and forget about it. Or copy/paste code snippet (scroll down past first couple paragraphs). https://www.quora.com/How-is-an-S-box-constructed-in-AES
Chani · 2020-10-22 00:24
>>21548 Thanks for taking a look. I originally copied the table, but then started reading about the rinjdael field and wanted to include the initialization. For the sake of progress I'm gonna proceed with hard-coding it for now. My frustration is that I can't see why anything would affect the portability of the snippet I found (on wikipedia S-box page), but maybe that's my unfamiliarity with C or the snippet was wrong in the first place
Frank Garza · 2020-10-22 03:00
>>21550 >I can't see why anything would affect the portability of the snippet I found I agree. Are you sure you aren't either doing something wrong with the array you feed to it or made a mistake with your testing function? If you really want to make sure that code is doing what it's supposed to, just put some extra code in debug fences that computes the multiplication and division with * and /, and then use assert(correct == p) or whatever to make sure it's not some weird behavior regarding bit shifts (there's a decent amount of undefined behavior relating to them, and unintentional implicit casts can fuarrrk things up.. although nothing is jumping out at me from the code you posted).
Knuth · 2020-10-22 11:45
>>20768 >>20769 >>20770 >>21550 >>21538 On page 30 of this PDF https://engineering.purdue.edu/kak/compsec/NewLectures/Lecture8.pdf it shows an S-box for encryption and a different one for decryption (tables in decinal not hex). You mention "ECB", AES has several modes and ECB is easiest to crack. They are teaching you not to use it in practice as well as teching skillz. The different algorithms have differences but the S-boxes *should* be the same. >>21548 You mixed up making a Multiplicative Inverse table with a S-box table. Nice try, try again. :/ >>21553 Absolutely! put in #ifdef DEBUG ... #endif blocks. Galois Field multiplication doesn't follow normal rules of arithmatic BTW, he should write a little function that does the XOR'-ing procedure. Also, write C code as a library (either header library or link/compile library). That way it can be used in driver/test programs. >>21550 The C programming language is not the problem (this time), but you may be encouraged to use Python more... Honestly the algorithm is complicated. :/ >>21543 The assembly language constructs depend on the CPU and sometimes other factors. You can see how your compilier does it this way. // compile with: cc -S hello.c && cat hello.s // on x86_64 it will *probably* invoke `doit()` as // call *%rax ;; a register-indirect call, // (works on my machine) other CPU and/or OS may be different #include <stdio.h> typedef int (*fn_t)(const char*); // should be type-compatible int main() { fn_t doit = puts; doit("Hello, World!"); return 0; } Some CPU's have a indirect call instruction or it may use another mechanism (i.e. pushing address on stack and RET). Typical stock CPU's may not optimize for indirect calls... But there are ways to do it. A Harvard Architecture machine might have instruction pointers of a different size than data pointers. >>21544 Correct. >>21541 Using uint8_t avoids the need to have &= 0xff; all over the place. *shrug* >>19723 based >>21527 The stories are great. What you use today will also become obsolete. The greatest optimizer is in between your ears. >>21538 Oh, since GF multiplication by 0x03 is "full cycle" this do-loop scans for the inverse... Just use a lookup table! I should try this as an exerciss but you complete the challenge. Good luck! >How the hardware works, etc... Not on nodern architectures! https://queue.acm.org/detail.cfm?id=3212479 https://twitter.com/meaningness/status/992974023737790464?lang=en It *can* be a reference point to compare architectures with, but modern computers don't work that wau anymore.
Unidentified · 2020-10-22 14:59
>>21554 >uint8_t avoids the need to have &= 0xff; all over the place That wasn't the part I was commenting on. The argument looks like a 256 byte array, but it's functionally just a uint8 pointer in this case. New C programmers often get confused about the distinction between stack arrays and pointers and dynamic arrays and such (and in which situations the distinction between them matters), so I just pointed it out in case he thought it meant something it doesn't. I've certainly been in plenty of situations where my code was inexplicably broken but then when I stepped through it in gdb it turns out I accidentally cast a pointer to a pointer pointer, or let a stack array go out of scope or something. >Galois Field multiplication doesn't follow normal rules of arithmatic In GF(2) isn't it just isomorphic to the integers mod some prime? I could be misremembering.
Bobby Newmark · 2020-10-22 18:39
>>21541 The expected behavior is to generate the LUT correctly, which I can tell by comparing to the table posted by >>21548 I was curious too about specifying array length in an arg like that. What my code does instead ` uint8_t Sbox[256]; initialize_Sbox() { ...` And the output when I print Sbox is ` 63 97 c6 e2 36 e3 0 e3 b3 97 42 58 50 d5 42 97 4a bb 7c d5 8d e2 f0 85 58 e2 9f bb 8d 1 7c c6 25 0 e2 25 c6 f0 a1 36 1 bb 0 e3 d5 d4 37 9f f0 b3 0 d4 d4 85 e2 9f 12 4a 12 25 c6 66 36 e3 24 97 50 1 0 a9 24 9f b3 9f d5 f0 9f d5 b3 7c 12 c6 e2 58 50 f1 42 d5 a1 37 e3 a9 f1 8d d4 4a d5 0 4a 42 50 d5 e3 24 e3 50 a9 7c 0 1 d4 12 85 37 24 1 85 b3 24 f1 36 4a bb d4 b3 97 42 97 66 bb 7c 8d 58 24 12 bb 50 f1 37 f0 66 f1 d4 9f 4a b3 d4 24 a1 36 a1 1 d4 66 a1 9f 4a e2 c6 58 85 a9 36 42 50 7c f0 a9 58 a1 97 f0 8d f1 a1 85 9f b3 f1 f1 42 a9 37 36 97 0 1 8d e3 e2 25 f0 a1 24 50 bb 25 36 8d 7c 58 37 a1 37 42 66 66 25 42 e2 58 bb 37 36 c6 85 58 d5 12 37 e3 12 85 97 a9 f0 f1 1 66 bb 12 c6 a9 a9 4a 24 66 25 97 c6 b3 12 25 0 e2 1 e3 8d 25 85 7c 4a 8d 50 7c 66` >>21553 >>21554 I went back and printed p and q each iteration, and now I see that while p cycles through each byte correctly, the values of q are looping` p : 3, q : 6f p : 5, q : 25 p : f, q : 73 p : 11, q : 41 p : 33, q : 3f p : 55, q : 15 p : ff, q : 63 p : 1a, q : 21 p : 2e, q : 1f p : 72, q : 65 p : 96, q : 23 p : a1, q : 71 p : f8, q : 2f p : 13, q : 75 p : 35, q : 43 p : 5f, q : 51 p : e1, q : 5f p : 38, q : 35 p : 48, q : 13 p : d8, q : 61 p : 73, q : 4f p : 95, q : 55 p : a4, q : 33 p : f7, q : 11 p : 2, q : f p : 6, q : 5 p : a, q : 3 p : 1e, q : 1 p : 22, q : 6f p : 66, q : 25 ...` So I'm feeling more hopeful about pinning down the problem >>21556 GF(2) is just the integers mod 2. In the case of AES we make a "field of bytes" by first representing a string of bits as a polynomial with coefficients in GF(2), so 10110 -> x^4 + x^2 + x, then to keep it to 8 bits we mod out by an irreducible polynomial of degree at most 8. In the case of AES they use 100011011 -> x^8 + x^4 + x^3 + x + 1
Dr. X · 2020-10-22 19:48
I thought of a way to think about pointers and dereferencing int a = 10 : the contents of address a is 10 int * b = a : the contents of address b is address a is 10 &a + 0 == 10 &b + (&b - &a) == 10 (not sure if math is right, but something should work) &a + (&a - &a) == 10 That's my big revelation, that a variable is a pointer that resolves to its own memory address,
Rick Deckard · 2020-10-22 20:14
I'm looking to relearn C, is "C the Hard Way" a good book to get good at C? If not, why? and what would you recommend instead? >inb4 K&R
Sipho Nkosi · 2020-10-22 20:18
>>21566 With that insight, can you figure out why a[b] == b[a] as long as one of them is a pointer and the other is an integer?
Just another Random Lainon · 2020-10-22 21:02
The best parts of C are that it just works and that Unix is bound at the hip to it. Can we show some love for the C Preprocessor? Without it I would use a more fully featured language. It's not just for header guards and testing which platform you're compiling on. I use X Macros regularly to make maintaining long enums with associated declarations and functions an order of magnitude more pleasant.
Ein · 2020-10-23 18:49
S-box guy again. I found the bug! There actually was an error in the snippet I pulled from wikipedia. In the multiply p by 3 line, 0x1B should be 0x11B. I submitted an edit to the Rijndael_S-box page
Yuki Nagato · 2020-10-23 19:24
>>21568 Neato.
JARGON · 2020-10-23 19:37
>>21567 K&R
Stallman · 2020-10-23 19:38
>>21585 >0x11B You mean 0xBB?
let · 2020-10-23 22:20
>>21590 I don't think so, what makes you say?
Roy Batty · 2020-11-14 15:49
A minor question regarding the coding style: do you typedef your structs or do you consider doing so a blasphemy (like Linus Torvalds does)?
Dujour · 2020-11-14 16:27
>>22177 I don't typedef then, but I also don't consider it a blasphemy. I just like the idea that code should be easy to read, not easy to write, and typedef is better for the latter, but as a hobbyist programmer, the former is more important for me.
Pris · 2020-11-14 16:29
>>22177 As I don't write C professionally (or even publicly, as I tend to not publish my code anywhere, really), I don't follow a strict style. Usually, when I get sick of writing "struct whatever" on a single project, I go on a rampage of typedeffing every struct I defined for that project. I usually like not typedeffing otherwise, as I think it looks more clear, if that makes sense.
synchronized · 2020-11-15 02:03
>>22179 never do such heresy as typedefing structs when you do stuff to release to others you are making understanding what kind of data is present harder The "struct Shit" makes it evident it's a struct and how to for example copy that and how to embed it as a part of other structs etc. There are plenty of reasons why it's better to not typedef structs. Pro of doing so is only a laziness.
Drifter · 2020-11-20 06:07
>>20805 >GNU software is some of the most robust, portable, and documented software available. kek my sides. go away Stallman
Koichiro · 2020-11-20 17:50
>>22196 >There are plenty of reasons why it's better to not typedef structs. I'd like to hear them. As to it being heresy: the Linux kernel and Linus's preferences aren't the end all be all of C. Loads of public, well respected libraries use struct typedefs. It is purely a matter of personal opinion. The most convincing argument either way is consistency in a large project, but unfortunately a vocal minority of people are more concerned with defending their one true way than getting things done.
protected · 2020-11-21 10:18
>>22379 treat that as an exercise in software engineering and readability hints - copying, align, casting, mixing cases and conventions and others
Terzibashjian · 2020-11-21 23:37
>>22392 >copying, align, casting None of these are impacted by using typedef. It's just creating another name for the struct. Readability in a clean library interface is a completely different thing from readability in millions of lines of kernel code. It's completely relative. If readability wasn't relative, then there wouldn't be dozens of styles that were created by people who thought they were reasonable only to wind up reviled when taken out of their original context. To typedef structs or not is almost on the same level as what variable naming convention to follow.
setq · 2020-11-21 23:51
>>22402 Yes they are. Think harder.
The Fin · 2020-11-22 03:20
Some basic example of good use of typedef is https://man7.org/linux/man-pages/man2/signal.2.html I dont have much things to say about typedef, I thing about this one like about "gotos" I know goto have nothing to do with typdef directives to preprocessor, but I treat they with a single rule: If it works and dont turn the code into something impossible to read in a few weeks its valid for me.
Faye Valentine · 2020-11-22 03:40
>>22408 congratz on giving a totally abysmal example of typedefs, mixing typedef and function pointers should be a criminal offense
Netrunner · 2020-11-25 19:43
>>19705 If this is how you're going to argue on this imageboard then keep your comments to yourself. There is nothing in this post that has any value at all. >>19829 There are some valid points in this video, but he often fails to state reason as to why something he does is better than something else. I agree with him about operator overloading introduces code that is being hidden from the user, not knowing what it does exactly and his point about garbage collection. He starts losing me when he talks about C standards and how he likes C89 because... C99 is buggy? Too new? Apparently having to define variables is a C only thing? He is talking about how he programs C, which is implying he is talking about C having this feature which makes it better than all the others out there, which just isn't true. Another point is naming conventions for functions. Having a space between the function name and parentheses apparently now makes it impossible to search for this function because of the space. The argumentation on this point is complete nonsense because if you decide you want to search for that function, why not put in the space and parenthesis? It doesn't break anything at all. Something that sadly triggers me is his spelling. The first 30 minutes of this video are horrible to sit through with about 2 spelling errors on every "slide", which don't contain a lot of text. The guy should have a look at spelling words, for his sake. It really doesn't feel like it's worth to watch any more of this as I think this tendency of not properly explaining why he prefers things a certain way and misrepresenting the C programming language will keep going, even though I really like C myself. I don't recommend watching this. >>20160 >just don't copy his habit of using microsoft-specific "_s" safe functions (ex. fscanf_s) What's wrong with those? >>20769 >My friend who knows assembly, told me I won't know how computer really works, If I learn C. It's not about knowing every little thing you can when people say "you learn how a computer works if you use C". It's about simple things like allocating memory by yourself, using pointers, etc. that give beginners a feeling to how a computer works behind all the abstraction and hand-holding of higher-level languages without needing to dive in head first into assembly, which is a way harder but also way more informative introduction. Although I agree that saying "it teaches you how a computer works" is a bit inaccurate. >>20805 >the baroque mess known as Unix Elaborate why Unix is a baroque mess >they love the edit, compile, run cycle so much that they avoid the use of configuration files [...] This is old and dumb. Since the 70s, it's been possible to redefine arbitrary functions during runtime. It's about keeping the program simple. Redefining functions during runtime is possible, sure, but it's also unnecessarily complex for the programs they write. Also, thanks to >>20827, you put it nicely.
Jet Black · 2020-11-25 20:12
>>22533 >Elaborate why Unix is a baroque mess Not that poster. I'm a unix fanboy even but I'll take a shot here. I'll start with proper unix from the era when posix mattered. Even barebones unix is a half-planned organic mess of whatever people decided they like. Why is configuration (sometimes) in etc? What does etc mean? https://ask.slashdot.org/story/07/03/03/028258/define---etc You can find similar questions about the origins of /usr, Many of the unix commands are little jokes and there is limited consistency in their namings. We still have to lug around all the old soykafty versions of these commands to preserve unix behavior in addition to our modern re-implementations (/bin/sh, more instead of less) Now we're deviating from proper unix and new directories and configuration files are created all the time. So many configs will now break everything if you edit them manually. I mean these are all minor gripes for me and impact me very little since I know unix pretty good. But wouldn't I love a unix-like system with all the software that had greater consistency and everything was named logically.
aliased · 2020-12-17 22:32
C is so fuarrrking bad, you can't even easily tell if your unsigned integer will be indeed treated as unsigned. Even with: uint16_t x = 123; uint16_t y = 456; instead of x + y < z That _still_ doesn't tell you how the result of x+y will be interpreted. You have to go look what type z is. If z is an int, then < will treat its arguments as signed, but NOT SO FAST: if your platform has 16-bit ints, then x+y will be treated as unsigned. Same soykaf for uint32_t: if your platform has 64-bit ints it behaves different than one with 32-bit ints. And I'm probably missing some detail here as usual, as C is an endless rabbit hole of discovering "LOL NOPE that construct doesn't do what you think it does". No other god damn language has this problem. Not assembly, not Ada, not Java, not even the most garbage fad language like Solidity has bullshit like this. In fact, this reminds me, the only language comparable to how bad C is, is JavaScript. You have 2 options as a newcomer: 1. look up some stupid fuarrrking C tutorial (such as K&R), and get a 60% correct answer, and write shoddy code 2. read the spec. but wait, then you notice it cost $100 Euros. you then go into a fit of cognitive dissonnance for the next hour with thoughts like: >does anyone even use the spec? why should I if nobody else does? >should I use the C99 spec for my C89 code? >should I just use C99/C1X/C2X? >is C99+ not good for some reason? >doesn't C99+ defeat the purpose of using traditional C for portability? >I typed "C89 spec PDF" into google and it gave me some bullshit PDF on some obscure website, should I be retarded and assume that's the correct spec? >should I do another 3 hours learning about specification organizations and the naming conventions of their specs to see whether this weird string ISO/IETF43235 TC REPORT 9000 is the thing I'm looking for? >do people even read the spec? maybe compilers don't even care about the spec and there is just some de-facto C language that everyone uses which has nothing to do with any spec? Now imagine you just came from programming assembly fulltime for years, and are familiar how with typical languages work, and then used some C. You want to pass an int somewhere? fuarrrking noooooo, it will get casted or some bullshit. You may fiddle around with the code for a minute until it does what you want, and then it wont work on any other platform. Now also even printf does some uninituitve garbage when printing %x of a negative number. You will have to go read the stupid printf documentation for an hour and learn the [[[domain specific language]]] before understanding that you can do %ux. Just every fuarrrking thing in this terrible language is a huge work to learn. Learn type declaration syntax next, enjoy wasting a few more hours of your life for what is trivial in every other language, and then forgetting it because it's obscure bullshit, then coming back and repeating. You have to be IN. SANE. for apologizing to this bullshit. This language is such an insufferable pain in the ass. The more I use it the more I am amazed by the abysmall lack of self awareness of the creators. They could not have designed C this way if they looked at just ONE other language invented between 1960 and 2020. THIS is why C is DOG SHIT. The whole "it's low level you are not real man" argument is a strawman. C is just a fuarrrking terrible language, regardless of how close to the machine it is. I have programmed assembly full time, and still use it once in a while today, and that does not make C easy to understand one bit. I see universities teach EE's to "just write some simple C code like this to set these 3 registers", and of course the moment they try to do any real application, their code will completely blow up, and now you understand why embedded industry is so soykaf (and im talking waaaaayy before IoT). I just remembered how stupid integer promotion is today and thought I would write this rant, and watch oblivious robots with their heads up their ass reply with "you're just not smart, C is simple". pic semi related
Ein · 2020-12-17 22:33
I meant: uint16_t x = 123; uint16_t y = 456; x+y < z instead of 123+456 < z
Moore · 2020-12-17 22:36
>>23418 The behavior is documented, go look it up. 99% of your problem is you're a lazy retard who can't be bothered to look soykaf up and read.
cdr · 2020-12-17 22:39
wait %x is unsigned and %ux is not a thing, so i cant remember the problem with printf. but basically theres some case where it obnoxiously converts your stuff to the sign you dont expect
Boole · 2020-12-17 22:42
>>23420 >%ux explain how that makes sense when hex is a bit-for-bit dump.
byte · 2020-12-17 22:42
>>23419 >standard robot response: i am going to ignore the fact that C is full of stuff that is complex for no reason and blame the user >upcoming robot response: i will continue to assume stuff is needed for performance or some mystical reason when they have absolutely nothing to do with performance I've read the entire specs of other languages. For C I don't bother because it's needlessly complex garbage.
BloodCat · 2020-12-17 22:43
>>23422 >I've read the entire specs of other languages. For C I don't bother because it's needlessly complex garbage. Press X to doubt.
Lady 3Jane.. · 2020-12-17 22:57
>>23423 Here is a list of rhetorical questions I posted for the sake of ridiculing bad languages (but not as bad as C) while reading specs of said languages: https://stackoverflow.com/users/2213023/dog I know PLs. Deal with it. I don't read C spec because it's literally pointless. Literally 0.0001% of C programmers program to the spec (be it C89 or a newer one). It's the language with the highest ratio of people who do not know what they are doing and writing non-conformant constructs. Now let's talk about code reuse in C. You fuarrrking have to publish a header file that hopefully matches your source code, and people hopefully use that same header. BUT NOT SO FAST: The header is a pile of macro garbage and potentially fuarrrks up your code, not even with name space clashes like the typical language, but it can even redefine macros and soykaf on you in other ways. The whole way you can reuse a piece of C code is by convention, whereas in other languages they provide proper facilities while being better in every way, and even less bloated (simpler implementations, despite having better features).
Haruyoshi · 2020-12-17 22:58
s/ratio/percentage/
Anamika · 2020-12-18 00:25
>>23424 >Here is a list of rhetorical questions I posted for the sake of ridiculing bad languages (but not as bad as C) while reading specs of said languages: https://stackoverflow.com/users/2213023/dog I like you, mate.
Stallman · 2020-12-18 01:06
>>23424 >rhetorical questions I posted for the sake of ridiculing bad languages Amusingly, most of the responses are pointing out your ineptitude with those languages. Seems more like a PEBKAC problem.
HELIOS · 2020-12-18 01:17
>>23427 >PEBKAC problem >Problem EBKAC problem
Nobody special · 2020-12-18 01:24
>>23428 You might think you're clever, but it's a well-known error to make https://en.wikipedia.org/wiki/RAS_syndrome
Turner · 2020-12-18 01:38
>>23429 Whoever came up with that self-referential term was a genius.
St. IGNUcius · 2020-12-18 01:41
>>23431 It is super amusing
Void · 2020-12-18 03:46
>>23427 >Amusingly, most of the responses are pointing out your ineptitude with those languages. Seems more like a PEBKAC problem. Are you familiar with the term "rhetorical question"? I'm starting to think Ctards are unironically autistic, or from Southern US. Almost no Java programmer knows about memory ordering and word tearing.
vector · 2020-12-18 05:03
>>23417 >2. read the spec. but wait, then you notice it cost $100 Euros. you then go into a fit of cognitive dissonnance for the next hour with thoughts like: Are you ever a dumb piece of soykaf. You were refuted on this very point in another thread. The spec is available online for free. Just search it. Jesus fuarrrking christ, how fuarrrking stupid are you?
Spooky · 2020-12-18 05:05
>You were refuted on this very point in another thread. Yes, I remember someone said "no" as a rebuttal.
Nobody special · 2020-12-18 05:22
>>23436 Nope, it was me, and I provided a link because I know you're a bad faith piece of soykaf. http://www.open-std.org/jtc1/sc22/wg14/ Don't you hate being called out like that?
Tank · 2020-12-18 07:54
>>23433 >I was only pretending to be retarded Your stack overflow questions are weak low hanging fruit. "Why [language] not handle unicode well? Why [thread unsafe code] bad? How [functional vomit] work?" They're all posted years ago so I assume it must have been a fun hobby for patting yourself on the back in highschool about how much programming you knew. I'll admit I lol'd at >A sensitive operation in my lab today went completely wrong. An actuator on an electron microscope went over its boundary, and after a chain of events I lost $12 million of equipment. If anything the fact you don't have any bait in C shows it's more simply designed. You have to be extraordinarily familiar with the language to make anything confusing or disgusting, and you can't just scan the spec for bullet pointed gotchas. Your nebulous complaint about namespaces in >>23424 falls flat when you consider that the lack of namespaces allows for a simple ABI, which is a huge factor in C's longevity. Nobody wants to write bindings for hideous C++ mangled identifiers. The macro preprocessor could be better, more hygienic and all that, but you can ask it if you're redefining a macro. Every new C programmer gets MACROS ARE EVIL drilled into their head anyway.
Lord Nikon · 2020-12-18 10:09
>>23440 You're much better off ignoring this attention whore.
Von Neumann · 2020-12-18 22:21
are there SDL2 tutorials but C? all the tutorials i found were in C++
Agent Jones · 2020-12-19 00:23
>>23455 I used Lazyfoo to learn SDL2. It's in C++, but you can easily convert it to C.
Nobody special · 2020-12-19 00:33
>>23417 Yess, yess, let it flow. Anyway, C is like a natural languahe you have to read a lot of it, and write a lot of it, to be proficient. You too can just start writing and correct the natural mistakes that breed from lack of familiarity. I would invite you to my party, seems to me you'd be fun to have around.
Nobody special · 2020-12-19 04:36
>>23455 If you're not comfortable with C++ (it is actually very similar to C, so it shouldn't be too difficult to grok), then I would recommend reading the text of the tutorial, observing the way functions are called in the source code (ignore the supporting code, focus on direct arguments and order-of-operations). From there, use the reference to understand the functions in detail.
Iverson · 2020-12-19 23:49
>>23437 I was (and still am, mostly) talking of ANSI C. Once again, that page does not contain a free spec for ANSI C. Linux is written in ANSI C (or something close to it), as well as most crap on top Linux, such as git and gnome. I remain unconvinced that anybody programs to any C spec, let alone document what spec their project targets. Searching again brought up this SO post, which confirms what I said: https://stackoverflow.com/questions/17014835/where-can-one-find-the-c89-c90-standards-in-pdf-format >>23440 >>A sensitive operation in my lab today went completely wrong. An actuator on an electron microscope went over its boundary, and after a chain of events I lost $12 million of equipment. Well, that example is certainly not low hanging fruit, and I highly doubt you understand it anyway. "It's not thread safe" just reeks of some vague concurrency 101 understanding, and is not sufficient to produce correct concurrent code (even if you "just lock" everywhere as a result of strictly following some rule you got from concurrency 101, which also happens to enforce memory ordering, you will still get deadlocks and much more complex issues). Almost no programmer would understand that it is a bug to construct an object and pass it to another thread without a lock or something that makes the write visible (99% of Java code is full of non-visible writes that "worked on my machine" in the first place), unless they've delt with memory fences. The intuitive interpretation - given that this is a high level language - would be that the object is constructed, then passed with a _visible_ write to another thread. Java even goes out of its way to do this for immutable objects (final fields). The Ctard/"I knew it hah u didnt trick me" interpretation would be that the object is passed to another thread without any synchronization at all - and this would be wrong too because of final fields. And this was from reading the JMM section of the spec, as opposed to your silly "you can't just read the spec and find edge cases" statement. I regret adding the opening about the microscope, since now I cannot tell if all these retards are in that thread just because of it or they actually understand question being asked. On HN it got some hundreds of upvotes and all the comments except for 1 or 2 were completely off topic, so I don't think any of them really understood anything either. The rest of your post is based on misunderstandings and I don't really feel the need to address it.
stack · 2020-12-20 00:04
>>23479 Ah, so when the facts don't mesh with your argument, move the goal posts. Also, since you are an expert, tell us the exact difference between the cited standard and ANSI C. Please, let's know why having the "ANSI" in the name on the cover makes any difference whatsoever.
Dujour · 2020-12-20 18:40
Anyone knows any interesting/well written in C codebase implementing Finite Element Method type simulations?
Project 2501 · 2020-12-20 18:52
>>23480 >move goal post nope, you just assume the goal post is on C99 for some reason. maybe read the thread? >>23417 i will restate my point about specification: C programmers do not write conforming programs. they do not even understand any spec aside from maybe reading a few clauses. most C programs do not specifically target C99. since they do not target C99, they usually target something like C89. since there is no easily available spec for C89, coupled with the fact that any C spec is exponentially harder to read than even a bigger language like Java, coupled with the fact that most Ctards only read K&R at best, it's obvious that almost nobody writes conforming C89. C is THE most important language w.r.t writing conforming programs not only because UB results in RCE, but also because the language has exponentially more UB than any other language, yet it is has the least disciplined users (not even undisciplined, but lots waste discipline on supporting "real world" instead of the spec. which is why C/UNIX is thousands of hacks). C programmer culture is anti-intellectual and argue with anyone who is "academic", maintaining the delusional narrative required to keep their culture alive: that "academics" do not understand the metal or live on false abstractions. any attempt to solve a problem is met by "wah too academic because im too lazy/stupid to understand/conceed". im sure even C89 was rallied against by thousands of meatheads back when it was proposed.
Project 2501 · 2020-12-20 18:54
>(not even undisciplined, but lots waste discipline on supporting "real world" instead of the spec. which is why C/UNIX is thousands of hacks) a more succint way to put this is that the more disciplined ones outright ignore the spec.
Yamaoto Toshi · 2020-12-20 20:06
>>23486 >well written >in C He just did it, the absolute madman!
BloodCat · 2020-12-20 20:14
>>23488 Most real life large C projects are tied to specific compiler not C whatever year's standards. >>23490 Go to the therapy Rustard. I hope no Lisper would be that retarded to actually write what you wrote here
Delilah · 2020-12-20 20:36
>Most real life large C projects are tied to specific compiler not C whatever year's standards. Yes. Actually, most well written code is in C, which describes the state of the software industry in a nutshlel.
Junichi Fujiwara · 2020-12-20 20:46
>>23493 I'm not sure what you mean by that. Most C code is horribly written, so if you're trying to claim otherwise you're wrong. But if you're saying that C's the language with the best written code by comparison, I'd be inclined to agree.
dictionary · 2020-12-20 20:53
>But if you're saying that C's the language with the best written code by comparison, I'd be inclined to agree. I was saying this.
Batou · 2021-01-05 22:19
Hi Lainons, do you know of any popular C libraries or frameworks that extend the standard library like Boost does for C++? Or even less than that, I'd be happy just having some more extensive data structures. I oftentimes sit down to a problem that I know would be fun to solve with C, but it discourages me when I realize I'd have to implement a basic list or a hashmap yet again. I'm not keen on writing C++
Dox · 2021-01-05 22:53
>>23741 why not c++? the STL is what you're looking for
McCarthy · 2021-01-05 23:48
>>23742 I know there are other languages. Some even provide packages, fancy modules and whatnot. I'm curious about the landscape of C libraries and whether there are any prominent ones that Lainons use.
Project 2501 · 2021-01-06 01:34
>>20104 I read (part of) this book back when it was still in "beta" and free (I think in 2014?). It was decent and definitely a fast track to getting started, but it's very opinionated and gave me some bad habits I've had to unlearn over the years. One of those being its "macro pack" containing error checking macros. Nobody does that in the real world, if() suffices, and everyone reports errors in their own special snowflakey way anyway. I haven't checked it since, as it became paid, but I wonder if it improved.
Undisclosed · 2021-01-06 01:38
>>23741 Glib is at least decent. It's installed on every linux system and you can use its data structures without buying into the entire framework if you want to.
Hagbard Celine · 2021-01-06 08:51
I just finished reading through K&R, as opposed to >>20085 I think it was written very concise and in a language I could understand well (I kind of expected it to be as hard to read as most manpages but it is way more comprehensible than any manpage I have ever read) Now my goal is to be able to contribute to unix software I care about or potentially write my own larger projects. What are the next steps? I assume you will tell me to just practice but when I write code for myself nobody will tell me that I use a bad style and I fear building bad habits. Reading source code of *BSD, git or suckless utils are on my list but I don't think reading only will get me to a level where I would be comfortable with sharing my code. I did some basic bin exploitation challenges so I know about some common vulnerabilities but they were all stuff that every compiler would have warned me about anyways. So how should I proceed to become a respectable contributor to foss peojects as soon as possible?
t · 2021-01-06 16:40
noob question here: Why does printf("%i", '0'-'!'); print 115151515151515151515151515151 ? From my understanding of ASII it should be 15, no?
string · 2021-01-06 16:53
>>23750 Untested speculation: your %i prints an int, but you're feeding it a character, so it's printing a bunch of uninitialized garbage out of the rest of the register. I think %hhi is the correct format string (or you can just explicitly cast the argument to an int).
Apoc · 2021-01-06 17:14
>>23751 Quoting from "The C Programming Language": >By definition, chars are just small integers, so char variables and constants are identical to ints in arithmetic expressions. This is natural and convenient; for example c-'0' is an integer expression with a value between 0 and 9 corresponding to the character '0' to '9' stored in c, and thus a valid subscript for the array ndigit.
Cat Mother · 2021-01-06 20:45
>>23750 what platform are you on, wigger? it just prints 15 for me as expected. your number cannot even fit into a 32 bit integer. it's amazing how none of the C ubermensch can even answer such a basic question about their language both numbers will be promoted to integer and then subtracted. i dont see how your output can happen but im not a C pro >>23751 >i think in terms of implementation instead of the language, but some imaginary implementation that only exists in my head basic wigger LARP >>23752 what fuarrrking garbage book just explain integer promotion is 'a' an int or char? i would assume char char - char first promotes each argument to be as big as int at least, as per >>23417
Six · 2021-01-06 23:49
>>23746 Awesome, that seems to be exactly what I need. It provides everything I was missing.
setq · 2021-01-07 00:24
>>23752 You probably get yel ed at by modern compilers if you try to pull that off. I'm not a C hater but that does seem like the kind of "trick" that obscures the code and makes little sense. Then again C is like a natural language with strange idioms you pick up
Six · 2021-01-07 08:29
>>23751 >>23766 ???? Did you ever write something in C or any other programming language that is not Python? chars are ints and that makes them useable, show me how you would write a function that counts each letter a-z in the input and stores it in an array, without using char substraction. I'll wait larpers. >inb4 switchcase lmao
nibble · 2021-01-07 13:38
>>23756 >both numbers will be promoted to integer and then subtracted. No, they're promoted to integer after the subtraction, since it's the implicit type of any variable-length arguments.
Nameless · 2021-01-07 13:56
>>23750 Maybe it has to do with the fact that, depending on your architecture, chars might be signed and negative if the leftmost bit is 1. Not sure if that could lead to the problem
Sipho Nkosi · 2021-01-07 15:15
>>23766 I'm just saying, modern compilers usually require you to cast explicitly. Then again I haven't used C in a while.
Sipho Nkosi · 2021-01-07 22:36
>>23772 yeah, not trusting a laintard on that. this example seems to show otherwise: #include <stdio.h> int main() { unsigned char a=255; unsigned char b=255; int lol = a+b; printf("lol: %d\n",lol); int jej = a+b; printf("jej: %u\n",jej); }
The Plague · 2021-01-07 22:37
lol: 510 jej: 510
hash table · 2021-01-08 12:32
>>23424 >https://stackoverflow.com/users/2213023/dog All I see is some autist thinking they're clever but making a fool of themselves.
Spooky · 2021-01-08 15:17
>>23790 I was in an interview the other day. For part of the interview, I talking to one of the developers about why he liked the company. >"It's great. I'm glad they convinced me to take the job. I only wish I had left my old job sooner." >"Really? What's the biggest difference between working here and your old place? Why are you so glad you switched." >"The people here are really great. At my earlier job, you'd occasionally see people ridicule each other for not knowing things or try to blame each other. I've never had that happen here. Everyone is very supportive of each other and trying to learn more on their own." I got an offer but didn't take the job, but it made me think a little. Meanwhile: >All I see is some autist thinking they're clever but making a fool of themselves. Wouldn't it be more honest to say "ur wrong and dumb"?
McCarthy · 2021-01-08 19:42
>>19673 Do i need to know assembly for embedded software, or c/c++(python) would be more than enough to build my robowaifu >inb4 just learn crisp
Naomi Nascimento · 2021-01-08 20:08
>>23810 You can do embedded purely in C, but it'll be hard to understand certain parts without some knowledge of assembly and computer architectures. "How do interrupts work?" "Why are these constants used as pointers?" You can do robotics in JavaScript on an Ubuntu desktop install with a System on a Chip computer. This can fit into a piece of hardware the size of a meaty book. It won't be adequate for hard time constraints.
push · 2021-01-08 20:54
>>23811 But is it difficult to get a job as embedded pleb to get some practice? Don't wanna look like a retard who thinks he is a hacker after pointing to "hello worl".
Y.T · 2021-01-08 21:16
>>23790 >you are dumb, not me this is coming from a thread full of C Larpers who do not even know how integer promotion works.
word · 2021-01-08 21:34
>>23815 I mean it takes less than 10 minutes to figure it out yourself. #include <stdio.h> #include <stdint.h> int main() { uint8_t a = 30, b = 40; printf("%u\n", (a * b)); printf("%u\n", (uint8_t)(a * b)); }
roll · 2021-01-09 23:10
>>23814 I don't know. From what I can tell, most of the people on this website know C in the context of Unix, so they wouldn't know either. I think if you buy any microcontroller that isn't an Arduino and write code for it, you will impress other people. (Not that an Arduino isn't impressive, it's just much less so because it has a great SDK that works out of the box. It doesn't take a lot of grit to get an Arduino "Hello World" set up.) The simplest project you could do that's meaningful is to build a small shell for your micro controller and talk to it from a PC over UART with minicom. https://help.ubuntu.com/community/Minicom There's a lot of guides on this. At that point, you an extremely simple OS. You could spend as much time as you want trying to add multitasking, persistent storage, or a loader. You could turn the shell into something like GDB: inspect and write to random physical memory addresses by command.
Chani · 2021-01-09 23:16
>>23841 Damn, that's the soykaf. Thanks a lot, skimming through books gets on nerves without proper on hand practice.
Joe Bloggs · 2021-01-10 03:14
>>23841 ? I have had one position as a bare-metal C programmer for microcontrollers, while also doing some bluetooth and wireless work. I don't understand why you'd think people on here do not have an embedded background. Now, like 90% of my experience with C is linux-based but not just applications deveopment, I've also done a lot of high performance controls systems. These skills are easily transferable to embedded. To anyone with zero programming experience trying to get into embedded - good luck. These shops have very small software teams, and mainly only hire senior and principal level positions. I happened to get lucky with 2 small (3-5 engineers) teams in the first few years of my career.
Ein · 2021-01-10 18:40
>>23841 >an extremely simple OS >multitasking Note that you will need some assembly for this. I guess you could try to be clever with an event loop and pseudo-coroutines, but as far as I'm aware, an actual OS scheduler can't be done in pure C.
Lain Iwakura · 2021-01-11 20:24
Hi there folks. I am on vacation and decided to get my feet wet with C. I want to write a simple script that converts pdf to images doing some processing on the image. Rather simple stuff, but I seem to be stuck at reading the pdf. Do you guys happen to know of a good, libre pdf toolset for C? I just need to open the file and iterate over the pages. I've taken a look at GIMP and ImageMagick APIs. I am lost at GIMP, documentation seems to be none existent. ImageMagick's documentation is great, but its reading capabilities seem to be geared towards reading single page pdf files. I know this might be a bit of an odd thing to do in C, but I just wanted to get to know the language. And yes, I am well aware that it is stupidly simple to do in either Bash or Python, but the point was doing it in C.
Sipho Nkosi · 2021-01-11 21:20
>>23872 This is not a use case for C. Use python or something.
Wirth · 2021-01-11 21:43
>>23872 PDF rendering is not an easy thing to start out with, I'm afraid. Maybe start with something like epub?
car · 2021-01-11 22:08
>>23872 Since you're doing it to get to know C, maybe you'll want to do it without relying on a third party library. You're clearly thinking of the python/bash way to do it, but the point of using C (in a case like that) isn't to do the exact same trivial set of instructions in slightly different syntax. C really is more low-level and you get to manipulate sequences of bytes. You'll learn a lot more, and you'll be using C in it's domain. Of course this means looking into the pdf reference and finding out how to accomplish a specific task.
Unspecified · 2021-01-11 22:12
>>23872 >>23878 Oops I thought you meant extracting images. Yes rendering is harder. Maybe use ghostсript? Idk if they provide libraries though.
Chan Siu Ming · 2021-01-11 23:38
>>23872 I've heard that games try to avoid allocating to the heap for performance reasons. Is that true?
Von Neumann · 2021-01-11 23:38
>>23881 Sorry, meant to reply to OP.
Just another Random Lainon · 2021-01-12 00:16
>>19683 >chanwackies do you even know where you are?
Incognito · 2021-01-12 01:25
>>23853 Saving and restoring registers isn't a significant amount of assembly.
Crazy Jake · 2021-01-12 01:37
>>23881 It depends. Allocation and deallocation is expensive, especially if you do it all the time, so it's best to avoid it in the mainloop as much as possible, but it has its time and place, for example when loading in assets or when you need more runtime state. In many cases you can get away with allocating everything once, since many games lend themselves well enough to static limits (e.g. max number of enemies).
Cypher · 2021-01-12 03:11
>>23885 It doesn't matter if the amount is "significant" or not; the point is that if you don't understand assembly (and possibly some other things like memory barriers), you will not be able to do this by yourself. It just bears mentioning because this is a thread about C, so someone unfamiliar with OS context switching might think they can do it with just C and later come out frustrated when they realize they can't, at all. Also, understanding of interrupts is crucial, but that goes without saying.
Hououin Kyouma · 2021-01-12 16:32
>>23887 There's many things you need to understand about the underlying architecture when writing an OS, assembly itself is a rather insignificant part of it.
dictionary · 2021-01-13 04:05
>>23816 You didn't figure out anything. More was figured out previously in the thread already, including the small part of it that your example explores.
Jean Dupont · 2021-01-13 08:05
How can I learn writing secure C code? I learned it from "The C Programming Language" some years ago, but I haven't used it a lot since. I can write programs in C, but they are probably insecure. Any books that go into detail about this? I know about buffer overflows and similar bugs or vulnerabilities but I can't imagine any modern software has them, yet there are still many exploits every day. So how can I make sure my code doesn't contain any complex vulnerabilities I don't even know about?
Lukasiewicz · 2021-01-13 10:56
>>23881 avoiding memory fragmentation is really important for performance. by keeping things close together you avoid unnecessary cache misses. so it makes sense to have a unchanging consistent memory layout of flat arrays. these can either be static allocation or heap allocated at program start.
Void · 2021-01-13 10:59
>>23898 using a sized string rather than a 0 terminated char array (char*) would be a good start. struct string { char* str; uint size; };
Kay · 2021-01-13 19:12
>>23898 It really depends on the domain, and many issues are language agnostic. But in general I think there are more papers and guidelines to read than books proper. for the embedded safety side, a combination of these things is typical: - coding guidelines (i.e. MISRA-C), - extensive testing (achieve 100% branch coverage with Unit tests, target suspect areas with additional testing approaching 100% MC/DC coverage, plus high levels of coverage with system level tests as well), and - Maybe a touch of formal methods (with a tool like frama-c perhaps) - a complex requirements and architecture process (this can be useful, but it's really a large project/ large organization process. no one uses DOORS for their side project) - an additional set of guidelines for writing cryptography code. - for special projects some amount of hardening (Fault Injection Mitigation is one topic) For any of these you can find papers and articles discussing them. For less critical software, I'd say the linux kernel coding guidelines are a good to read. Also, you asked about security. The above is more about "safety." So I'd consider safety at the software level as only exhibiting intended behavior. Security I would say is about not revealing secret information. I'd read about constant time comparison if you're not familiar, it's easy to understand but you may never have thought about it before. The OWASP top 10 are the most common web vulnerabilities. Some of this stuff doesn't apply to the types of programs that you are likely to write in C, but it doesn't take much to look over the list and try and think if it could in some way apply to your program.
DEBUG-CONTENTS · 2021-01-13 19:17
>>23898 Modern software still has buffer overflows, or similar exploits. They can be harder to find than you think. Also, the C standard library is bad. don't use anything without considering alternatives or seeing if there is a fixed version of the function that is also in the c standard library. Are you aware of format string vulnerabilities?
Nameless · 2021-01-13 19:21
>>23909 >format string vulns Hilarious. printf("%s", fudge); // :) printf(fudge); //!!!!!! >:-)
Ivan Horvat · 2021-01-14 11:42
>>23900 Do big foss projects actually do this?
BloodCat · 2021-01-14 13:39
>>19673 Bros, how to learn C language in one month?
Chan Siu Ming · 2021-01-14 15:22
>>23930 Redis is an example of a project that uses a pascal style string library. (SDS) The Linux Kernel is an example of a project that does not.
Aristóteles Amadópulus · 2021-01-14 18:53
>>23853 >Note that you will need some assembly for this. I guess you could try to be clever with an event loop and pseudo-coroutines, but as far as I'm aware, an actual OS scheduler can't be done in pure C. You're right. I don't think there's anyway to do hardware aware multitasking without assembly. A way to cheat besides pseudo-coroutines: write a system VM and write the scheduler that uses VM assembly. >>23893 >There's many things you need to understand about the underlying architecture when writing an OS, assembly itself is a rather insignificant part of it. We're talking about writing a simple OS on a microcontroller. If you're only going to vaguely allude to "things you need to know" without specifying anything, why even say anything? It sounds like you're imagining virtual memory schemes, modern file systems, and high speed IO, but those are irrelevant.
Delilah · 2021-01-14 19:16
>>23931 Read the book. You know which one. If you're not sure then scroll through the thread.
swap · 2021-01-14 20:10
>>23940 The book won't teach what is used the most at work. The book teaches raw basics, but it won't amount to much if you have no idea how to implement them in big ass projects. So the question could be rewritten as, what actually i have to make bloody sure to learn, not to fuarrrk up tons of time(have to support family so not much of freedom and time on hands).
Random · 2021-01-14 22:37
>>23942 >not to fuarrrk up tons of time >in C That's a good one.
quote · 2021-01-15 02:56
>>23931 You don't learn any programming language in one month.
Armitage · 2021-01-15 03:09
>>23931 time isn't worth what it used to be, you can't do things so quickly anymore. the days have been shortened. if you still want to learn the way to learn is to make an application that does something. you can get feedback from that and then advance further. SDL is a decent library for opening a window and drawing rectangles and images, you could make a simple game or filebrowser or texteditor or something.
HELIOS · 2021-01-15 21:41
>>23947 You could learn c's semantics, tooling, and some standard library stuff in a month. But that wouldn't help you write software, really. It's like, do you want to learn hammering, or learn construction. Hammering alone is not really useful. >>23942 So as for this question, what type of software do you want to write? Why? Do you have a job lined up and you need to get up to speed? Are you looking for jobs? Do you want to contribute to your favorite open source project? Do you want to know how your computer "works?"
aliased · 2021-01-16 07:40
>>23963 My bad, didn't expect some serious answers. But in fact it's quite simple, waging on cheap place looks unstable with all rona stuff so i found several companies looking for microcontrollers engineers. As >>23948 said the best chance i have is to start making literally anything. >So as for this question, what type of software do you want to write? The minimum i want to know how protocols SPI/I2C/UART work(connectivity in general), and C of course to meet minimum criteria.
Splicer · 2021-01-16 13:43
How do you decide whether to use C or some other language for a project?
progn · 2021-01-16 13:55
How do you decide whether to use C or some other language for a project?
Koichiro · 2021-01-16 14:02
>>23973 You can use whatever you want. But some questions that can help if C is what you want are ones like: Is it going to have a GUI? Is speed important? Do you want to waste some time coding data structures? Is it web-based project? Do you want to code something fast? and so on
Mario Rossi · 2021-01-16 22:06
Please tell me why I shouldn't use macros, gotos and multiply dereferenced pointers
Boris Grishenko · 2021-01-16 22:25
>>23987 >macros You should use macros, but only for certain kinds of thing. It doesn't make sense to put substantial logic on a macro because it's like an inline function that's difficult to debug. >gotos This is more a case of there almost always being a better option. The only situation I can think of where they kind of make sense is for implementing simple exception-like behavior to error out of a loop and clean up before terminating. This might affect the kinds of loop optimizations the compiler can do though, so often it makes more sense to set a "success" variable to false and break out of the loop normally instead of jumping. >multiply defereferenced pointers Depends on what you're doing with them. If you want an array of arrays, it's usually better to do it as one big strided array instead.
Anonymous · 2021-01-17 00:19
>>23972 Write a driver for a little i2c based bitmap display. on some micro probably is easiest. Complicated enough to cover real ground, but not that hard. and fun to make pretty picture. For microcontroller stuff, other skills are as important as c. like for small companies using oscilloscope and protocol analyzers. for large companies how to work with the hardware engineers who will do that for you as long as you phrase the question right. Not "this code should work but doesn't" but instead "When I set this bit, I thought this hardware sequence should be triggered but I don't observe anything on the bus" And reading schematics. Not understanding the circuit, just being able to follow along with someone who really knows what they're doing.
Nguoi La · 2021-01-17 12:07
Im trying to learn C but i cant seem to find any compiler for Windows 10 any suggestions?
Bobby Newmark · 2021-01-17 12:24
>>24002 Install Gentoo
XERXES · 2021-01-17 14:50
>>24002 http://www.smorgasbordet.com/pellesc/ Windows is C++ land, in general. A unix environment will be the best for C but Pelles C is ok if you're stuck on windows for whatever reason. allegedly. Never used it myself.
string · 2021-01-17 18:18
>>24002 Not sure if this will run on Win 10 (I did used it on Win XP or Win 7 can't remember which one) but you might give it a try: https://bellard.org/tcc/ For learning purpose it should be OK... Or you could install cygwin and have a Linux like enviroment for programming... Or you could choose the middleground and install MinGW.
Haruyoshi · 2021-01-17 18:23
>>24008 Whoooe they have a link to a forum build on top of Simple Machines... This is soething I didn't see in a long, long time. Makes me smile.
Acid Burn · 2021-01-18 17:43
>>24002 can you not use gcc with the windows subsystem for linux?
Six · 2021-01-19 14:08
Is there a need in open source projects for someone that mainly parses the code and attempts to enhance its readability by adding comments and formatting it better? Or does your average contributor already does that whenever they add something themselves? I ask because I honestly suck at coding from scratch, however I'm good at deciphering already written code and I actually enjoy attempting to piece together the logic behind the various algorithms and loops. So I'm wondering if it's possible to apply that part only into open source projects, in an effort to make things easier for other contributors (who can actually improve upon the code).
Meddler · 2021-01-19 15:42
>>24042 There are a variety of different open source projects with different approaches and policies. But for the vast majority I'd say, no, do not do that, at best you'd be told to go away, at worst considered a spammer. For one thing, the others who contribute have a much better idea of what the existing code means. If you suck at coding from scratch but are good at deciphering already written code, I think you're over-estimating how good you are at deciphering already written code. Imagine the people who can contribute, their number one skill is also going to be deciphering already written code, but they can also write it. Your comments and formatting changes are not likely to be trustworthy. Unsolicited formatting changes are irritating. So what should you do? User guides, man pages, and tutorials. Very few projects have end user documentation that is fully accurate. However, you can't do this by just reading the code, you will need to understand the domain the tool is used in.
Davis · 2021-01-19 18:39
>>23972 Buy a cheap microcontroller and make sure to get one that has hardware SPI/UART/whatever because at a job you usually won't be bit banging those protocols. The most important part of embedded programming is READING. Read the datasheet, read the user manual, read relevant examples. Most dev boards hook one of the communication protocols up to the USB so you can make some toy programs interacting with your PC. It's highly unlikely you can get a job in embedded with no relevant education or experience unless you make something really impressive, so try to have fun. If you're really inspired, shoot for the stars and make something like a simple RTOS. >>24002 Seconding Pelles C. Unlike >>24008 I have used it a moderate amount, and my recommendation comes with a word of warning that you may encounter compiler crashes. If you stay away from C11 you should be safe, but I've had trouble with the floating point optimizer. >>24042 If a project is looking for documentation, comments, or formatting they will generally post about it wherever they track their issues. Soliciting formatting work is an easy way to get a characteristically terse reply from the project members.
Cypher · 2021-01-20 02:30
>>24002 https://sourceforge.net/projects/mingw-w64/
word · 2021-01-23 19:11
What is the best way to learn network programming in C? Would be good if the book would cover the basics of networking in general as well
Pris · 2021-01-23 20:58
>>24084 install python or anything. literally just not C
Otto Normalverbraucher · 2021-01-23 21:12
>>24084 I think the best way to learn any language is ad-hoc: start projects and then learn the things you need to make it work. It teaches you not only how things work but also where to use them. If you want a good starting point, try writing a median function. You'd be surprised how much it'll tell you about the language you're writing it in. >>24086 That doesn't answer his question.
sizeof · 2021-01-23 21:43
>>24086 >>24087 I should have been more clear: I already know C, I just don't know a lot about networking. Yes, obviously, it is faster to get started with the Python sockets lib but this is not what I want. People often tell me to read the TCP/IP specification but I think that would be a little overkill
hash table · 2021-01-23 22:42
>>24084 here you go my man https://www.beej.us/guide/bgnet/
nthcdr · 2021-01-24 11:48
>>24084 Read CSAPP, chapter 11. http://www.csapp.cs.cmu.edu/
John Rain · 2021-01-24 14:49
>>19742 >>19743 lol, this reminds me of when I was a student trying to optimize an example problem and wondering why my "a.out" didn't get faster. At some point I realized that I kept creating a faster program named "2". >>20044 Why not just use a Linux VM? >>21566 I'm very confused, do you mean *(&a + 0) == 10?
Ein · 2021-02-04 16:53
I'm new to C, currently learning what to do and what not to do. Is it a good idea to use unions in 2021? It seems terribly unsafe and I don't really get why I would ever need to use one. But maybe that is just because of my lack of experience.
Roy Batty · 2021-02-04 18:24
>>24311 I wouldn't call it unsafe, in the typical programming sense. Potentially error prone. I believe unions are the "correct" way to do bitwise operations on floats (instead of the old *(unit32_t *)&some_float technique) and tagged unions are a way to build Sum Types in C, which are a valuable tool. So I would encourage use of unions in 2021. But they don't come up that often, to be honest. Not in existing code bases anyway.
stack · 2021-02-05 00:44
What are good tools to start a new project in 2021? meson? automake/autoconf? Something portable and easy as rust's cargo build.
Ishikura "Tatsu" Tatsuhiko · 2021-02-05 10:01
>>24319 Shell script to run the build commands, makefile when that becomes unwieldy, meson when that becomes unwieldy. Don't use autotools under any circumstances they suck.
Kay · 2021-02-05 12:51
>>24311 They are good for example in limited memory cases when you want to have access to different size types of variables and save memory by making them occupy overlapping memory section. You can make use of that feature to implement some really deep arcane magic when dealing with implementing data structures or other stuff. some simple example at the end of https://www.geeksforgeeks.org/union-c/
John Rain · 2021-02-06 03:23
>>24311 for unions you have a `uint type_id;` indicating the current data it stores. tagged unions. in a game I store all entity types in the same struct and have a `uint type;` to indicate what entity it currently is. entities can have different entity specific data so that is put in a union to keep the struct size small and efficient. I just have an array of entities with a `uint size;` indicating current number of entities, and in the enity update and draw functions switch on the type to have different enity behaviours and appearances.
The Fin · 2021-02-06 06:39
>>24346 When you loop over the array you have to check the type of every entities union before using it or how does that work?
Unknown · 2021-02-06 09:04
>>24352 yeah every time you loop over the array of entitites you have to switch on the type. you have a case for every entity to give it specific behaviour, and as you already checked the type of the entity in the switch statement you can access that specific entity type's union data. if you modify or access the wrong union data it'll of course corrupt the data and give you garbage because they are stored in the at the exact same memory location. you could achieve a similar result by storing function pointers for update() and draw() within the struct and have pointers for extended entity specific memory. which is essentially how c++ virtual functions and inheritence works (vtables). I like having a single `type` variable that determines the entities update() and draw() functions (by switching on the type) and what entity type specific data. Only one thing to update, only one thing to go wrong. Also having all the data inside a single struct with no pointers for entity type specific data helps performance by improving cache locality. heres an incomplete example. struct Entity { uint type; float x, y; int hdir; //horizontal facing direction union { struct { int anger_tmr, anger_level; }; struct { int attack_tmr, attack_damage, attack_speed; }; }; }; enum EntityType { ET_NONE = 0, ET_ANGRY, ET_ATTACK }; void update(Entity* e) { switch(e->type) { case ET_ANGRY: if (e->anger_level > 0) { e->x += e->hdir; //move when angry e->anger_tmr--; if (e->anger_tmr <= 0) { e->anger_tmr = 60; e->anger_level--; } } // (entity_collide doesn't exist, just an example) if (entity_collide(e, ET_ATTACK)) { e->anger_level++; e->anger_tmr=60; } break; case ET_ATTACK: e->attack_tmr--; if (e->attack_tmr <= 0) e->type = 0; //turn it into ET_NONE, destroying the entity e->x += e->hdir*e->attack_speed; break; } } void draw(Entity* e) { switch(e->type) { case ET_ANGRY: draw_rect(e->x, e->y, 64, 64, 0xff0000); break; case ET_ATTACK: draw_rect(e->x, e->y, 16, 16, 0x0000ff); break; } } Entity entities[1024]; uint entities_size; void game_loop() { for(uint i = 0; i < entities_size; i++) { update(&entities[i]); } for(uint i = 0; i < entities_size; i++) { draw(&entities[i]); } }
Zero Cool · 2021-02-06 09:06
>>24352 >>24353 i messed up the example indentation heres it fixed struct Entity { uint type; float x, y; int hdir; //horizontal facing direction union { struct { int anger_tmr, anger_level; }; struct { int attack_tmr, attack_damage, attack_speed; }; }; }; enum EntityType { ET_NONE = 0, ET_ANGRY, ET_ATTACK }; void update(Entity* e) { switch(e->type) { case ET_ANGRY: if (e->anger_level > 0) { e->x += e->hdir; //move when angry e->anger_tmr--; if (e->anger_tmr <= 0) { e->anger_tmr = 60; e->anger_level--; } } // (entity_collide doesn't exist, just an example) if (entity_collide(e, ET_ATTACK)) { e->anger_level++; e->anger_tmr=60; } break; case ET_ATTACK: e->attack_tmr--; if (e->attack_tmr <= 0) e->type = 0; //turn it into ET_NONE, destroying the entity e->x += e->hdir*e->attack_speed; break; } } void draw(Entity* e) { switch(e->type) { case ET_ANGRY: draw_rect(e->x, e->y, 64, 64, 0xff0000); break; case ET_ATTACK: draw_rect(e->x, e->y, 16, 16, 0x0000ff); break; } } Entity entities[1024]; uint entities_size; void game_loop() { for(uint i = 0; i < entities_size; i++) { update(&entities[i]); } for(uint i = 0; i < entities_size; i++) { draw(&entities[i]); } }
Special Agent Bob · 2021-02-06 15:06
>>24354 Oh gosh, members of anonymous unions/structs a.k.a. strong typing go make love with yourself with their workaround of being "promoted" to be a part of parent structure/union (and so on and so on if parent is also anonymous). If something from newer standards make me have uneasy feelings - it's one of top candidates. They require additional book keeping and attention from both tools parsing code and programmers. The question is - are benefits being sold by adequate price. They can be used to introduce a lot of mess.
Masami Eiri · 2021-02-07 01:08
>>24360 yeah in a professional project you'd probably want to have the union be named and it's members be named as well to avoid confusion. like e->extra.angry.tmr; e->extra.attack.damage;
Batou · 2021-02-08 06:25
Does c pack structures in a compatible way? I have a string struct and a dynamic string struct. The string doesn't own the allocation, but the dstring does. I have functions on string that are applicable to dstring. I'd like to directly use the same function on dstring as on string to reduce code bloat. Will this work with modern hardware or software, or can it fail? struct string { char* str; uint size; }; struct dstring { char* str; uint size; uint max; }; //dstring additionally stores maximum availible chars char string_at(string s, uint at) { if (at >= s.size) return 0; return s.str[at]; } //inline so no code bloat inline char dstring_at(dstring s, uint at) { //the first members of dstring are the same as string, so can this work reliably? return string_at(cast(string)s, at); }
Unspecified · 2021-02-08 09:26
>>24376 >compatible In what sense? Fields are always in order you declare them. it may involve also some padding or not depending on order of fields and architecture's word size (machine's word sized memory reads tend to be faster than smaller reads on many architectures, yhats why padding is used to make sure read is multiplication of machine word in size). http://www.catb.org/esr/structure-packing/ https://en.wikipedia.org/wiki/Data_structure_alignment#Typical_alignment_of_C_structs_on_x86 Generally speaking there is no guarantee that padding between your struct members would not differ between both structs. C standard only guarantee there is no padding before 1st member. Your code may be OK for some platforms tho. Yet on other it may not work as expected. It may also depend on compilers. If padding between members would differ between your two struct types it would fuarrrk up results.
Jim Hilger · 2021-02-09 11:29
>>20169 Pointer is a variable that can change the values of other variables. One at a time. You use & to tell the pointer where to find the variable you want to change. Then You use * to tell the pointer to change the value of the variable that it's pointing to.
Milner · 2021-02-18 12:02
What methods of avoiding int overflow do you use? If you even bother.
typedef · 2021-02-21 13:07
>>24519 I rarely write anything where they would overflow. Just make sure the result of multiplication is a size class bigger than the source types, or the values are limited in such a way where that doesn't matter. For addition and subtraction, my value range usually just isn't big enough, and if it is, it's usually user input for which I can just assume the two's complement overflow semantics defined by POSIX are good enough, and I just check the value range of the result is acceptable. You'll soon learn that writing C is all about not dealing with stuff like this unless it *really* matters for your program.
Miho Iwakura · 2021-02-21 19:51
>>24568 >You'll soon learn that writing C is all about not dealing with stuff like this unless it *really* matters for your program. What if it's too late?
Lunch · 2021-02-21 22:59
>>24568 I had a jira the other day about a QA tester complaining that a test application did not do proper argument checking and wanted an engineer to fix it. My response was basically "who the fuarrrk cares? If the user wants to put in a negative number for this value, why should I stop them from being a moron? Maybe they want a timeout of -1? That sounds more than reasonable to me. These fine minutia just don't really mater unless the requirements explicitly say they do. It's not hard to check for an overflow condition and deal with it. Most systems I work on are completely indifferent to a counter being overflown, and that's actually their expected functionality (basically how any sequence counter works).
J.C. Denton · 2021-02-22 00:42
>>24571 In all honesty, I prefer something being wrong to actually *tell* me it's wrong rather than silently "handling" it by just using the values and ending up with nonsensical results. If I wrote a negative number for a timeout, it's more likely to be a typo than something intentional, as it makes no sense. This happy avoidance of handling errors is what leads to things like "null island", where an invalid location maps to a valid coordinate. This tends to happen more often as more things pile on top that don't do their own checking and handling either. That said, especially in C, checking for and handling any kind of occurence like this is a fuarrrking nightmare, so you're better off not bothering unless you really have to or it can cause security/stability issues. Also keep the audience and scope of the tool in mind before you drown yourself in error handling.
Lady Jessica · 2021-02-22 10:46
>>24571 Tester was 100% right. >>24572 >That said, especially in C, checking for and handling any kind of occurence like this is a fuarrrking nightmare, LOLWUT?
HELIOS · 2021-02-22 20:25
>>24571 Feed -1 as a ti eout and it'll hang for 2^64 seconds
Jane Doe · 2021-02-24 12:08
C has poisoned me - it is the only language that sticks in my brain.
BloodCat · 2021-02-24 12:16
>>24589 Same. I'm more productive in other languages, but writing C that is small, fast and functioning, is just damn satisfying.
cond · 2021-02-25 08:15
>>24591 >>24589 C is a drug because it supports coders with a constant feel of own superiority over code monkey crowd pleb corpo slaves implementing yet another system for managing temperature and humidity level in a warehouse of a retail chain of rubber sex dolls.
J.C. Denton · 2021-03-01 01:57
Does anyone know where to find a simple desription of linux ELF binary data structures? I want to programmatically make a library from a single binary data file. I only need the char* address, uint size, and the char[] binary data blob stored/accessible in the library. I know you can use ld -r -b binary -o text_1.o sample1.txt To get that result, but I'd prefer to be able to do this directly in my program itself. I'd just be combining in a string: the elf header, the binary data blob, and the address & size of the blob with symbol names so I can access them in c. The only thing I'm having trouble with is finding relevant documentation of the format thats readable and has the relevant data types and structures necessary for this.
aliased · 2021-03-01 02:31
>>24729 man 5 elf https://linux.die.net/man/5/elf
byte · 2021-03-04 03:07
Thoughts on this extremely basic proof of context text editor? #include <stdio.h> #include <stdlib.h> #include <sys/stat.h> #include <unistd.h> #include <fcntl.h> #define BUF_SIZE 8096 int main(int argc, char* argv[]) { if (argc != 2) return 1; int c, i = 0, fd = open(argv[1], O_RDWR | O_APPEND); char buffer[BUF_SIZE]; printf("Enter text, when finished type ctrl_D\n"); while ((c = getchar()) != EOF) { buffer[i] = c; ++i; if (i == BUF_SIZE-2) { printf("Maximum character input reached, ending."); c = EOF; break; } } write(fd, buffer, i-1); close(fd); return 0; } Currently going throuh Advanced Programming in the Unix Environment and trying to get the hang of file I/O with some basic projects. I was hoping for some tips on how I could improve this tiny program.
Boole · 2021-03-04 03:46
>>24749 1. Print an usage string to stderr if the argument count is not valid. E.g.: fprintf(stderr, "usage: %s <filename>\n", argv[0]); 2. Check the return value of open(2), because it returns -1 on error. To print the error, use something like perror(3) or strerror(3), or err(3) if you're using BSD libraries. 3. Useless 'break' at the conditional inside the loop. You can either set c to EOF, or break, but you don't have to do both. 4. I think you can write characters in the buffer up to BUF_SIZE-1, and then write 'i' amount of characters via write(2). 5. Since you're using O_APPEND, maybe you can print the existing contents to console to give a hint to the user that they are appending? 6. No newline at the end of the "Maximum input reached" printf-statemen