[a / b / c / d / e / f / g / gif / h / hr / k / m / o / p / s / t / u / v / vg / vm / vmg / vr / vrpg / vst / w / wg] [i / ic] [r9k / s4s / vip] [cm / hm / lgbt / y] [3 / aco / adv / an / bant / biz / cgl / ck / co / diy / fa / fit / gd / hc / his / int / jp / lit / mlp / mu / n / news / out / po / pol / pw / qst / sci / soc / sp / tg / toy / trv / tv / vp / vt / wsg / wsr / x / xs] [Settings] [Search] [Mobile] [Home]
Board
Settings Mobile Home
/g/ - Technology

Name
Options
Comment
Verification
4chan Pass users can bypass this verification. [Learn More] [Login]
File
  • Please read the Rules and FAQ before posting.
  • You may highlight syntax and preserve whitespace by using [code] tags.

08/21/20New boards added: /vrpg/, /vmg/, /vst/ and /vm/
05/04/17New trial board added: /bant/ - International/Random
10/04/16New board for 4chan Pass users: /vip/ - Very Important Posts
[Hide] [Show All]


Janitor applications are now closed. Thanks to all who applied!


[Advertise on 4chan]


File: 1781114380999.png (157 KB, 598x799)
157 KB PNG
What are some C tricks that /g/ knows?
>>
C is a joke of a language
>>
>>109024221
if this blows your mind you're a mohammedan rapebaby
>>
>>109024221
use case for not having a semicolon?
>>
File: 1770472659228524.png (26 KB, 715x592)
26 KB PNG
>>
>>109024389
Is this just x-- and checking if it's greater than 0?
>>
>>109024464
no, it's the "goes to" operator, didn't you read the explanation?
>>
>>109024221
The best trick is to ditch C and learn a more inclusive language, specifically Rust.
>>
>>109024389
funy
>>
>>109024221

void swap(int* a, int* b) {
*a = *a ^ *b;
*b = *a ^ *b;
*a = *a ^ *b;
}
>>
>>109024221
This is peak jeet
>>
You no longer have to type "void main" because "int main" now returns zero by default.
>>
>>109024221
You can declare a function as a function parameter.
It works like declaring an array, i.e. it just decays to a function pointer, but it will confuse people and spark fun conversations.
>>
>>109025283
I thought you can only do that in JavaScript
>>
>>109024221
What a retard.

#include <stdio.h>

int
main(void)
{
return (
printf("Hello chud"),
0
);
}
>>
>>109024221
Try writing your C in functional programming style. Make every function a single statement that returns a value.
Watch as this makes Lisp and Haskell programmers seethe!
>>
int main(void){
return printf("whoever reads this is now a faggot") * 0
}
>>
>>109024791
Coming from C, I just ask:

”Explain this to me as a c programmer, and make it make sense”. Worked very well so far.
>>
>>109024791
>muh rust trannies saar, not like badass C which is close to the hardware, i learnt malloc last week in CS50 at durgasoft classroom saar
You will never be a systems programmer Pajeet Singh, go ask ChatGPT to generate your fizzbuzz final project
>>
File: 1767084272428361.gif (2.37 MB, 640x350)
2.37 MB GIF
Duff's device:
int send(char* to, char* from, int count)
{
int n = (count + 7) / 8;

switch (count % 8) {
case 0: do { *to++ = *from++;
case 7: *to++ = *from++;
case 6: *to++ = *from++;
case 5: *to++ = *from++;
case 4: *to++ = *from++;
case 3: *to++ = *from++;
case 2: *to++ = *from++;
case 1: *to++ = *from++;
} while (--n > 0);
}
}
>>
STFU you racist bigot. C is dead. Long live Rust.
>>
>>109025688
doesn't work because no closure (and that's a good thing)
>>
>>109024841
This is why we need 128 bit ints. To hold all our <= 16 byte strings and swap them if need be.
>>
>>109025688
Does C have tail recursion optimization?
>>
>>109026416
> Headline: latest rust2c transpiler has rustaceans on suicide watch
>>
>>109025972
https://www.chiark.greenend.org.uk/~sgtatham/coroutines.html
Coroutines using the same idea
>>
>>109024221
There is a DWORD but no NWORD.
>>
>>109024841
Based space ooooptimizer
>>
>>109024280
literally posted by a streetshitting hindu
>>
>>109024293
Spending bytes to save bits.
>>
File: 1324497404001.jpg (35 KB, 600x518)
35 KB JPG
>>109026843
Ah but there are lots of SHIDWORDS
>mfw decompiling
>>
>>109026980
>>
>>109024293
semicolon cancer is rising among younger adults, with no clear reason why, experts are warning
don't you read the news
>>
>>109024221
It doesn't matter what the if statement evaluates to retard
>>
>>109024389
>// x goes to 0
Can you supply a proof of this fact? pro tip: show that x-- is less than x when x > 0
>>
File: 1761460276810.png (12 KB, 624x331)
12 KB PNG
You can use O2 to remove useless overflow checks(because overflow CAN'T happen).
>>
>>109027815
in shitty versions of c*
>>
>>109026765
Of course it has.
With optimizations at level 2 in GCC this recursive FizzBuzz is compiled to code without the recursive call and only one branching jump for the loop:
#include <stdio.h>
static int f(int n) {
return n > 100 ? 0 : f((
printf("%i\0FizzBuzz\0Fizz" + ((!(n % 3) * 12 + !(n % 5) * 7) & 15), n),
putchar('\n'),
n + 1));
}
int main(void) {
f(1);
}
>>
>>109024280
it was literally said by a jeet rapebaby. weird deflection, rajesh.
>>
>>109024791
how inclusive is rust of homophobic, transphobic, racist nazis? asking for a friend.
>>
Anon, just make your functions pure.
Decompose into simpler functions as much as necessary, implement loops with tail recursion, take advantage of ternary operator, short circuiting, and comma operator so each function only has the return statement.
I.E.: Print an integer as Roman numeral.

typedef struct {const char* str; int v;} RomanPair;
static const RomanPair romanPairs[] =
{{"M", 1000}, {"CM", 900}, {"D", 500}, {"CD", 400},
{"C", 100}, {"XC", 90}, {"L", 50}, {"XL", 40},
{"X", 10}, {"IX", 9}, {"V", 5}, {"IV", 4},
{"I", 1}, {0, 0}};

#include <stdio.h>
static int printRomanPair(int n, const RomanPair* p) {
return p->v && n > 0 &&
(n < p->v ? !++p : printf((n -= p->v, p->str)),
printRomanPair(n, p));
}

static int printAsRoman(int n) {
return printRomanPair(n, romanPairs);
}

static int test(int n, int max) {
return n < max && (
printf("%i : ", n),
printAsRoman(n),
putchar('\n'),
test(n + 1, max));
}

int main() {
return test(1, 4000);
}
>>
File: images_2.jpg (13 KB, 225x225)
13 KB JPG
>>109024221
Functions and ternaries as L-values
*complicated_lookup(index) = val;
*(bool ? &val1 : val2) = val;
>>
>>109027722
x-- is always smaller than x, no matter the value of x. Especially since you're not supposed to have overflows if you ode properly (better turn on -ftrapv).

You may think you're smart and that x-- isn't always smaller than x when x = INT_MIN, however unless you explicitly tell the compiler how to behave in cases of signed integer underflow, then the compiler is free to optimize away your comparison to 'true'
>>
>>109024841
in good langs with destructive read, this is just
a = b = a
>>
>>109024791
Good morning ma'am
>>
File: w.png (62 KB, 1433x180)
62 KB PNG
>>109027825
overflow/underflow behavior is platform specific. Unless you instruct the compiler how to behave, then the compiler is free to assume IT NEVER HAPPENS. Because the standard says it's your responsibility to make sure you aren't retarded, which the compiler cannot yet enforce
>>
>>109026765
C doesn't have it in the standard. But most compilers will optimize recursion into a loop whenever they can. So it's not a hard guarantee, but depending on your target/platform you can assume it's the case
>>
>>109028564
Irrelevant since it took til very recently for the "standard" to even give you tools without compiler specific intrinsics to even do basic checked/wrapping/saturating arithmetic. C is shit.
>>
>>109026670
GNUC has closures, though the syntax is vomit-inducing

Here's a nested function that captures it's environment:
int x = 0;
void plus(int a) { x += a; }
plus(15);
printf("%d\n", x);


And here's how to make it anonymous:
// gcc -z execstack a.c && ./a.out
int x = 0;
void (*plus)(int) = ({
// closure-local variables declared here..
int z = 2;
void inner(int a)
{
x += z * a;
}
inner;
});
plus(15);
printf("%d\n", x);
>>
>>109028590
>platform-specific behaviors require platform-specific tools
Honestly, the standard is just lacking. IMHO there shouldn't be a standard library, just the core language features should be standardized, because of how fucking retarded FILE* is, everyone should use vendored api, like unix's fd or windows file handles.
>>
>>109028618
are there even any C programs that are portable thanks to the standard library?
>>
>>109028611
yeah, fuck that
>>
>>109028618
malloc() and the string.h and math.h stuff is nice to have but i don't think any of the I/O is that helpful
>>
>>109028618
nothing makes you have to use any of the standard libraries
>>
>>109024841
It's nice except without optimizations it's much slower than the temporary swap.

I like this swap, but it relies on overflows
void swap(int *a, int *b)
{
if (*a == *b) return;
*a -= *b;
*b += *a;
*a -= *b;
*a *= -1;
}
>>
>>109028072
>printf
impure io piggu

You may do this:
```
int
main
(
argc
,
argv
)
int argc;
const char* argv[];
{
printf("Hi I'm %1 and I'm a faggot!\n");
return
0
;
}
>>
>>109028611
Honestly not as bad as you claim, it's certainly better than Sepples lambdas.
>>
>>109028632
malloc should just be provided by the vendor. on some platforms malloc always return null because malloc doesn't make sense compared to a single arena allocator.

math.h is 99.9% of the time optimized away by compiler-builtins, which generate cpu-specific instructions (depends on architecture). On gcc you have to explicitly dynamically link libmath otherwise -lm is optimized away using compiler builtins, resulting binary doesn't even link against libmath.so.
>>
>>109028656
you have to tell math.h to fuck off sometimes too, bc builtins are enabled by default and math.h blocks your path to naming a function "log".
>>
>>109025972
satanic
>>
>>109028656
I know math.h is always optimized out, but a lot of its functionality isn't actually available without a lot of work. I think it should be fine to have "standard library" features that can actually be implemented by the compiler, whether its linked or not is irrelevant.
>>
File: f.png (357 KB, 1082x2101)
357 KB PNG
>>109028647
I built a format 'function' that works like python/c++/rust format function.

Though the code is very ugly and relies heavily on compiler builtins.

You can just do something like
format(&fmt_stdout, "Hello, {}! 64 in hex is {:x}. Printing object: {}", "foobar", 64, (object, object_formatter))

it supports optional positional arguments and custom formatter
>>
>>109028664
>blocks your path to naming a function "log".
When will cniles learn what namespaces/modules are?
>>
File: branred.png (156 KB, 768x2109)
156 KB PNG
>>109028669
Agreed, math.h is very high quality (if you're referring to IBM's libm which is used by glibc)
The people who built it made tons of publications about how to efficiently sqeeze more precision out of builtin floating point types.

I read through some of libm's code a while ago and it's littered with gems if you're into multiple precision floating point computing
>>
>>109028673
they're called "translation units"
>>
>>109028626
It's generally the opposite, especially on linux, because the most widely used standard library has tons of additional features that are tempting to use. If you use any of those, good luck porting to another platform (which means another libc)
>>
>>109028690
Nah, linking requires each linkable function object to have a unique name. If you don't get the error during compilation, you'll get it at link time. There are ways to tell the linker to use your function instead of libm's log, but that's not a real solution.

In other languages, this is solved by mangling function names, like rust that uses a random identifier, or gnucxxabi that uses a complex naming scheme based on namespaces and function parameters
>>
>>109028688
right now i have to do a bunch of fixed point trig and its really fucking gay
>>
>>109028709
you make it sound like name mangling is a good thing
if i'm #include'ing math.h, i'm not going to be defining a function named log, that's silly
>>
File: cos.png (52 KB, 825x552)
52 KB PNG
>>109028710
for sin/cos, libm does this:

1. reduce argument to the [0, pi/4] range (you can reconstruct the [0, 2*pi] using simple symmetries that don't lose any precision

2. decompose reduced argument into x + dx where x is a known value from a lookup table (for 64-bit float the LUT has 110 entries), and dx be as small as possible

3. You plug in the sin(a+b) or cos(a+b) identity:
sin(x + dx) = sin(x) cos(dx) + cos(x) sin(dx)

Now, thanks to the lut, you know the exact value of cos(x) and sin(x), and since dx is small, you can use a simple first order approximation (taylor series):
cos(dx) = 1 and sin(dx) = dx

The trick is to chose the perfect table size to make this last approximation accurate. Using these, libm is able to get below 0.5 ULP, which is really good for a library.
>>
X-Macros are really cool and I felt like a C-super-wizard when I learned about them for the first time. Apparently they also predate C and were used first in the preprocessor of some assembler. Preprocessor tricks are really cool and much more so in C where macros are by their nature more a hack than something meant to be used extensively. X-Macros, unlike other preprocessor tricks, are also actually useful and not just a little gimmick, such as when creating opcode tables for emulators.

https://en.wikipedia.org/wiki/X_macro
>>
File: x.png (26 KB, 701x129)
26 KB PNG
>>109028805
they're nice. I've used them in a couple of projects to create 'type traits' in C
>>
>>109028746
yeah i redid basically exactly that, except i had to add in a multiplication and division step to "multiply" the angle by pi because the angle is not in radians
>>
>>109028833
except i diden't do the cool dx shit, i just approximated it as linear up to the point that it no longer worked to my required decimal precision and then went to a dumb taylor approximation with an adjustment term. I did the same symmetry stuff though
>>
>>109028833
Also, libm needs to handle all type of arguments, but if you're just doing rendering, then you can enforce that your argument always lies in the ]-pi, pi] interval, which can simplify the logic quite a bit.
libm also has to deal with nan/inf, subnormals and denormals whic you probably don't need with fixed point arithmetic

I'm no expert on fixed point, so there are probably other tricks that can be used to increase speed/precision that otherwise don't work on floating points.
>>
>>109028858
no its really dumb chud embedded systems work but i felt fancier than just doing a lookup table lol
>>
>>109028869
lookup tables are the dirty secret of performant code
>>
>>109024221
>>109024273
>>109024280
You’re literally reading a post by an indian and thinking you’re going to see genius when everything they post is “I’m a 12 year old child and I fundamentally misunderstand everything.”
>>
>>109029089
We cooking stone soup bruh
>>
>>109027287
Kek‘d
>>
>>109028947
>lookup tables are the dirty secret of performant code
not really. they're a technique, but they aren't always the fastest.
>>
>>109028564
Nope, read k&r first edition. It's up to the programmer.
>>
>>109031179
this, they drastically slow down longer pipelines that modern processors have. it's usually faster to use a taylor series, even though it executes way more instructions.
you can test it out using llvm mca:
https://llvm.org/docs/CommandGuide/llvm-mca.html
>>
>>109024293
An if wrapper is just more elegant.
>>
you can give this guy money and he'll continue to fight to revitalize your dead language and you can read about the existential dread it makes him feel. that's a good trick imo

https://thephd.dev/finally-embed-in-c23
>>
>>109028641
this is slower than temporary swap and you allocated a new stack frame to enter this stupid fucking function
>>
>>109024791
Based, unironically.
>>
>>109027287
Lol
>>
>>109028858
>libm also has to deal with nan/inf, subnormals and denormals whic you probably don't need with fixed point arithmetic
Fixed point math doesn't have NaN, Inf, subnormals or denormals at all. That makes some things easier, and some things a lot harder (and there's not so much hardware support for it outside of basic ops).
Essentially, fixed point is better at addition/subtraction than floating point, and the reverse is true for multiplication/division. Float's automatic scaling benefits some things, and hurts others.



[Advertise on 4chan]

Delete Post: [File Only] Style:
[Disable Mobile View / Use Desktop Site]

[Enable Mobile View / Use Mobile Site]

All trademarks and copyrights on this page are owned by their respective parties. Images uploaded are the responsibility of the Poster. Comments are owned by the Poster.