[ 3 / biz / cgl / ck / diy / fa / g / ic / jp / lit / sci / tg / vr / vt ] [ index / top / reports / report a bug ] [ 4plebs / archived.moe / rbt ]

Due to resource constraints, /g/ and /tg/ will no longer be archived or available. Other archivers continue to archive these boards.Become a Patron!

/g/ - Technology

View post   

[ Toggle deleted replies ]
File: 8 KB, 248x175, union.jpg [View same] [iqdb] [saucenao] [google] [report]
69183648 No.69183648 [Reply] [Original] [archived.moe] [rbt]

What are the most niche language features you have come across.

C/C++ Union is up there for me. I have only had one case where it was useful for providing a weak polymorphic interface.

>> No.69183703

It's pretty common. But by my standard I can't think of anything niche.
They're entirely different between the two. C++ doesn't allow 'type punning'. Which drastically changes the utility of this feature.

>> No.69183732

C trigraphs are way up there for me. Absolutely ass-backwards.
Unions have their place and they're really beautifully useful to aid in obfuscation, too.

>> No.69183748

JS 'with' is pretty niche. It would be nice in certain OO situations, but it's bad practice to even use it unfortunately. Something about security problems.

>> No.69183759

Creating your own datatypes in MATLAB, I still have to find any official documentation for it's existence.
At first this was some kind of oral knowledge, as the only reference I had was my professor mentioning how to do it.

>> No.69183801

>C trigraphs are way up there for me. Absolutely ass-backwards.
Didn't those exist because keyboards in some regions did not map those characters to any key.

>> No.69183945

C doesn't allow type punning either. I think it has relaxed rules regarding structs with common initial sequences but otherwise it's still illegal to dereference an int* cast to a float*.

Template template arguments in C++.

>> No.69183986

That's not the same thing as the special case of union 'type punning'.

>> No.69184002

union Float{
float num;
bool sign : 1;
int exponent : 8;
int mantissa : 23;
} parts;

>> No.69184036

I think you mean this.
union Float
float as_float;
struct { uint32_t sign : 1, exponent : 8, mantissa : 23; };

>> No.69184127

Here, lisbstdc++'s std::string short string optimisation. Uses unions.
namespace std _GLIBCXX_VISIBILITY(default)



#pragma GCC diagnostic push

#pragma GCC diagnostic ignored "-Wabi-tag"

// Redefine __sso_string so that we can define and export its members

// in terms of the SSO std::string.

struct __sso_string


struct __str


const char* _M_p;

size_t _M_string_length;

char _M_local_buf[16];


union {

__str _M_s;

char _M_bytes[sizeof(_M_s)];

std::string _M_str;



__sso_string(const std::string& s);

__sso_string(const char*, size_t n);

__sso_string(const __sso_string&) noexcept;

__sso_string& operator=(const __sso_string&) noexcept;


__sso_string(__sso_string&&) noexcept;

__sso_string& operator=(__sso_string&&) noexcept;


>> No.69184136

By the way, you should use std::variant, much safer and more verbose.

>> No.69184157

I didn't even know about that, thanks. For me it would have to be generators in JS. Higher order functions or objects are more flexible, I don't know why they were added.

>> No.69184195

We use unions all the time in embedded development to express register settings though typically it has to do with signals that are less than a byte wide.

>> No.69184211

This mess of underscores is what makes STL completely unreadable.

>> No.69184215

>less than a byte
You sure it's not bit fields?

>> No.69184228

It's not publicly interfaceable code, you're not supposed to read it.

>> No.69184235

That's necessary to avoid leaking names. Identifiers with double underscores are explicitly reserved for the implementation.
Modules will fix this.

>> No.69184263
File: 1 KB, 125x70, 1544395397139s.jpg [View same] [iqdb] [saucenao] [google] [report]

I really have to think hard of how I could possibly use this in my program...

Then again I have memory leaks galore, so I suck.

>> No.69184300
File: 144 KB, 646x914, 1534473716737.jpg [View same] [iqdb] [saucenao] [google] [report]

Both of you should fucking die with those 4 spaced indentations.

8 spaced means you wont end up with pyramids of conditionals.

>> No.69184310

Except that from time to time you need to know how it works under the hood.

>> No.69184314

no u

>> No.69184325

I used this shit in flex/bison to make a simple compiler

>> No.69184347

Unions (and variants) really have no good usecases. They're a morbid form of dynamic typing and they break the fundamentals of C/C++.
They should only be used by experienced pros.
>from time to time
The only reason to know that is if you're reimplementing the std::containers for fun/exercise. You're not supposed to know how or why they work, only how to correctly interface them.

>> No.69184396
File: 42 KB, 680x684, 1503347954077.jpg [View same] [iqdb] [saucenao] [google] [report]

Its only for saving memory as far as I can tell.
The java generation will obviously not give a fuck about such things, but it would be important.

To me, I could probably switch some of my enumerator oriented code... to a union, but... I dont think it would make things more readable, which is more important to me.

>> No.69184429

>variants are dynamic typing
You really have no idea what the fuck you're talking about. Algebraic types are about as far from dynamic typing as it gets.

>> No.69184470

If you don't know a type compile-time, it ain't static typing. You want some unrealistic arbitrary code, go write python.
It's like I can just tell you're a first year student. Memory is uninteresting. ISO C++ makes no mention of "cache" or "register" keywords (register exists but has null effect). Anything beyond working code is opti/pessimisation.

>> No.69184498

The type is a sum of types, just like a tuple is a product of types. You don't understand anything.

>> No.69184501

I saw a nice pattern for packing and unpacking network packets using a union of pointers recently.

>> No.69184506
File: 53 KB, 800x723, 1540380903946.jpg [View same] [iqdb] [saucenao] [google] [report]

>pays someone to teach him how to program
found the java fag

>> No.69184531

>sum of types
>product of types
CPUs only understand composition of types aka offsetof(). Go back to Haskell.
>reinventing the wheel over and over until it clicks

>> No.69184551

>reinventing the wheel over and over until it clicks

>> No.69184575

Having somebody just spill the knowledge and philosophy on you is better than gradually learning. It's all been discovered already, just pick up where others left off.

>> No.69184580

If you only care about what the CPU knows then you write assembly. We don't write assembly because dev time is more valuable than computer time. C++ exists to give us abstractions and sum types are a cheap and useful abstraction.

>> No.69184609

C++ gives you STL and the tools to extend it. That's it.

>> No.69184619

That's my point, C++ gives you efficient abstractions and the tools to write your own.

>> No.69184642

Okay so where amidst templates do unions come into play?

>> No.69184651

I'm not sure I understand your question. You can combine templates with unions to form variants, which are a cheap and useful abstraction. Isn't that the point of this conversation?

>> No.69184668

The conversation is on runtime type behaviour being evil.

>> No.69184688

No, because somebody can be anybody, and teachers dont tend to be people of virtue very often. Unless you really know that the guy is hot shit when it comes to programming, learning from Mr WindowsProgrammingEnvironment is a bad start.

If you want to learn well on your own, you do three things:
- Contribute to competent open source projects, so your code will be reviewed.
- Adopt the style and principles of the most well rounded projects, such as the Linux Kernel.
- Read the fucking manual, and read it well.

The only thing you need to be disciplined on, is finding out what you don't know.

>> No.69184722

Variants lack the inefficiency, unpredictability and lack of semantic information that actual type erasure does.
The type of a variant will inform you what its possible values are, and the interface of the variant will ensure you only perform valid operations on it. That's a far cry from actual dynamic typing.

>> No.69184741

Guaranteed any teacher with a bachelor and masters is better than any and all youtube celebrities.
Maximum code reading, minimum code writing. I am not wasting a year or two of my life to understand Linux well enough to contribute.
>style and principles
Minimum algorithms, maximum bike shedding.
>Read the fucking manual
I guess that's good once you pass the basics of the language, else you're just memorising unnecessary info.

I see no reason learning on your own is any better than having knowledge dumped on you.

>> No.69184757

So correct me if I'm wrong but a variant can hold different types at different times. How is that safe again?

>> No.69184863

The set of types which a variant can hold is constrained. A std::variant<Foo, Bar> only holds either a Foo or a Bar. With void* or std::any, you can't tell that by looking at it.

Additionally, the value inside a std::variant is typically accessed by pattern matching. That means you do something like this.
// this code can be cleaned up with templates but I want to keep it simple

std::variant<Foo, Bar> my_variant;

auto operator()(Foo foo)
// this function runs if the variant contains a Foo
auto operator()(Bar bar)
// this function runs if the variant contains a Bar

visit(my_variant, my_functor);

This way you won't accidentally call the wrong function on the wrong type. You can't - unlike dynamic typing.

>> No.69184868
File: 47 KB, 632x852, 1508997862012.png [View same] [iqdb] [saucenao] [google] [report]

TF are you talking about? No one mentioned youtube... Although I would agree that learning programming from TheNewBoston is not the best. But on the opposite end, you can just listen to a Harvard or Princeton Class on programming, all on youtube.

>I develop in notepad++. Vim takes too long to learn
Glad I dont work with you.

>not putting curly braces on if statements never hurt anyone. You just got to code

>I guess reading the manual is okay...
Its really fucking important long term.

>I see no reason learning on your own is any better than having knowledge dumped on you.

Two reasons:
1) You are purchasing cognitive dissonance, making it harder for you to drop bad habits.
2) Costs tons of money.

>> No.69184892

>8 spaced means you wont end up with pyramids of conditionals.
Or you could, you know, have some self-control. Also, just because they type code into the 4chan reply box with 4-space indenation doesn't mean that's how they normally write code.

>> No.69184895

That honestly looks like something you do under dev time constraints, a hack to outsmart the C++ type system.
>cognitive dissonance
?? You get to talk to young and energetic people and learn together. There's no equivalent on the internet, just anonymous buffoons recommending C for everything.
>tons of money
Ohhh you're American.

>> No.69184909

You wot m8? Yeah, you might not see them much in typical desktop application programming, but they're extremely common in any kind of embedded development and pretty much anything else sufficiently low level.

>> No.69184961

Compiler attributes.

>> No.69184975

You have not been programming for very long.

>> No.69185001
File: 73 KB, 960x960, 1512875106620.jpg [View same] [iqdb] [saucenao] [google] [report]


It forces self control. People who rely on willpower always fail, and only faggots like you pretend that it can be otherwise.

Indentation is meant for one thing: To clearly deliniate where blocks of code begins and ends. If you are running out of columns, reconsider your life as a programmer.

Thats it. Why anyone would use 4, or 2, or 1 can only be summed up as being seriously brain damaged.

Who in their right mind would for example want to contribute to code written like this:


>> No.69185015

I genuinely do not see a problem with that code, it's very nicely indented.
>same column == same thing
That's it, stop being autistic.

>> No.69185051

I disagree. If I'm working with a variant, I know more about what value it contains than if I used e.g. a pointer to a base class. I also get cheaper polymorphism (one cmp vs a stable lookup) and easy value semantics.

>> No.69185054
File: 733 KB, 855x534, 591de7c884835aa33e9adbd5cf045bd986f6dd477cf2835249685b8340324f64.jpg [View same] [iqdb] [saucenao] [google] [report]

Okay listen here Harbinder.

What happens when you or pajeet decide to comment out line 257?

>> No.69185057

>People who rely on willpower always fail
I bet you're fat.

>Why anyone would use 4, or 2, or 1
Maybe because they are typing it into the 4chan reply box where they'd have to press space a billion times instead of pressing tab twice?

>posting code with 2-space indentation as an argument against 4-space indentation
Nice strawman. Also, what is %s/ / /g?

>> No.69185096

I add an extra semicolon to show that the if body intentionally does nothing and that I did not comment out the line on accident?
Who comments out lines arbitrarily anyway? Sheesh

>> No.69185103

>I bet you're fat.
You wish you were as white as me.

>uses quick reply to write code
Not my fault people are gay.

recurring replace applied to a whole file.
Too bad it doesnt work in a web browser you stupid fuck.

>> No.69185104

Code indentation preferences were solved by tabs.
Like 4 width? no problem
Like 8 width? no problem
How anyone can justify using hard whitespace for code is beyond me.
Want it for ascii art? Fine.
Comment alignment? Whatever.
Code? Stop this.
Waste of time, strokes, and bytes.

>> No.69185121

Now that union is the accepted way to override strict aliasing, it's not exactly niche any more. Something like this though: https://hamberg.no/erlend/posts/2013-02-18-static-array-indices.html

>> No.69185147

I dislike this feature, I find "array" parameters in C to be misleading.

>> No.69185151

>You wish you were as white as me.
So you're fat. Also,
> being a white western male
> implying that's anything of a privilege
You'll be bullied to death just because you exist.

>> No.69185154

>criticizes people for typing 5 lines of code meant to be posted online straight into the web browser instead of firing up a text editor
>uses a web browser to inspect hundreds of lines of code

>> No.69185155
File: 87 KB, 1038x576, pajeet-code.jpg [View same] [iqdb] [saucenao] [google] [report]

Yeah who Pajeet?

>Clearly, people who take preventative measures to avoid bugs are just undisciplined.
Please, go back to phone scamming. You were far more useful there.

>> No.69185165

>You wish you were as white as me.
You're not white, you're pale. You look and probably are sick from staying at home all day.
Go out to restore your natural skin colour.
I'm not the one working with people who arbitrarily comment out lines of code. Fucking retard.

>> No.69185174


>> No.69185186

There is also the question, why would I want to program under someone who is braindamaged enough to indent in two spaces so he can addequetely nest loops and conditionals within themselves?

>> No.69185196
File: 522 KB, 975x1357, 1526236073731.jpg [View same] [iqdb] [saucenao] [google] [report]

You should rarely ever go beyond 3 levels of indentation, maybe 4 at most.
Staying true to this rule has led to cleaner code than any meme pattern or other dumb advice I've ever heard.

>> No.69185237

Agreed. The code you linked looks cleaner than it actually is because of the very small indentation.
Indentation should be nice and large.
8-character wide tab indentations leave no excuse and don't hide anything.
Good code looks good with them, shit code looks shit with them.

>> No.69185240
File: 129 KB, 500x390, 1541555145039.jpg [View same] [iqdb] [saucenao] [google] [report]

Almost that attitude alone would make me hire you.
Even in the worst case scenario, your code would still be readable and easy to correct.

>> No.69185249

True, the way that if it decays to a pointer if you pass an '''array''', but doesn't if you pass a pointer to an array is especially retarded. However, none of that is particularly niche; tons of real world C code relies on this behavior. This is about using static in them like int myfunc(char anarray[static 5]);, which is something I've never seen in the wild.

>> No.69185331

I used to think o too, and I mostly do this too (especially by negating ifs), but sometimes manually inlining your code works wonders.

>> No.69185340
File: 153 KB, 1011x1000, 1539639928842.jpg [View same] [iqdb] [saucenao] [google] [report]

You dont get it. Its not about commenting out lines

Its about not bracing if statements.

You are so crazy, that rather than adding

if (foo){}

you would rather

if (foo);

That is insane.

>> No.69185354

Can you send me a demo of what the fuck you're talking about?
>if (foo);
if (foo)
It sticks out like a sore thumb, nice and noticeable. I mean, you can add an assembly block with NOOP in it or something if you want.

>> No.69185377

>Can you send me a demo of what the fuck you're talking about?
What the hell don't you understand?
Some people think it's better to not have too many levels of indentation in the code.

>> No.69185433

if (foo)

Did you ever stop to consider that the tool used for merging code might not see things the way you do?

if (foo) {
// bar();

is safe from both user error, and from merge confusion.

The fact that you do not understand that, and completely missed the apple ssl reference, shows that you simply do not have what it takes to be a good programmer.

>> No.69185448

Aren't you the Anon claiming to be white?
Bracing single line if's is only necessary if you're working with people who don't understand the language.
Disallowing features of the language is stupid. If you can't trust a group of humans to deal with this detail then you shouldn't be trusting them with C at all.

>> No.69185456

I don't watch apple ssl or any other conferences than cppcon.
Hmm. No, having commented out lines is confusion.
>a good programmer
A programmer good if and only if he has a vast knowledge of algorithms and how to apply them. Beautiful code is not fast code.
Actually, beautiful code has to run slowly.

>> No.69185481

If you're going to move the goalpost from human to tool then your argument falls apart. We have tools to test functionality and automated review for a reason.

>> No.69185482

>use shitty language that requires manual cleanup code all over the place
>have no support for running block-level cleanup code automatically like all merely 30 year old languages do
>result is awful if() ladders everywhere
>claim that deeply nested indentation is a sign of poor programmers rather than the obvious language problem it is
>almost definitely a Cnile brainlet who thinks he's being '''smart''' by using gotos instead
What's not to understand?

>> No.69185493

I'm a C++ programmer and am literally above and beyond those issues.

>> No.69185496
File: 9 KB, 247x310, file.png [View same] [iqdb] [saucenao] [google] [report]

here's a use i like

>> No.69185503

>Can you send me a demo of what the fuck you're talking about?
What do you mean? You want an example of code that consistently follows this rule?

In that case, you have to look no further than Linux. The GitHub mirror page is correctly formatted and uses the right size for tabs: https://github.com/torvalds/linux . Big ass 8-character wide tab indentations, and rarely over 3-4 levels of indentation.

It's even in the kernel style guidelines themselves: https://www.kernel.org/doc/html/v4.10/process/coding-style.html

Of course, that's fairly easy to achieve in C, which doesn't have a lot of features, but it's perfectly doable in other languages such as C++, Java, JavaScript and Python as well, in my experience, if you're disciplined (you can allow an extra level if you're in a try-catch block).

Limiting your indentation is highly beneficial to code quality. I dare say it's the single most beneficial thing you can do for your code. And by using large indentations, you are forcing yourself to use less indentation levels.
It's like Ulysses tying himself to the ship to hear the sirens.

It's crazy that such fundamental advice is missing from the book """Clean""" Code. Instead, we have meme advice repeated over and over.
Keep it flat, keep it simple.

>> No.69185505


>> No.69185508
File: 143 KB, 400x400, 1505308645525.png [View same] [iqdb] [saucenao] [google] [report]

>tfw don't have mental breakdowns over syntax

>> No.69185525
File: 80 KB, 1059x1043, Untitled.png [View same] [iqdb] [saucenao] [google] [report]

Okay now THIS is epic

>> No.69185556

>claim that deeply nested indentation is a sign of poor programmers rather than the obvious language problem it is
>claim that deeply nested indentation is a sign of poor programmers rather than the obvious language problem it is
Deeply nested indentation more often than not *is* a sign of bad programmer skill, but it's also true that some languages encourage more nesting than others.

I'm not a fan of C, but it's not nearly among the languages which need the most indentation.
Have you seen fucking Scala? The official style guides literally encourage TWO character indentations due to how deep it gets even for simple programs.
Scala is a mess.

In fact, it's easier to write less indented code in C due to not having classes, try-catch blocks and the like. Deeply nested C code is even shitter in comparison to most other languages.

>> No.69185568

>Hmm. No, having commented out lines is confusion.
Sometimes, but it is generally fine if you have descriptive code. But in principle you are right, commenting should be placed in places to clear up what obtuse code is performing... However, something like this:
if (foo) {
doBar(); // This does bar.

is unneccessary. Also, commenting should be avoided if possible because the only thing worse than no commenting, is commenting that is no longer accurate:

>shouldnt be trusting people
who do not practice good style. I dont care if you are stephen hawkins or linus torvalds; code clearly, and put fucking braces on all your conditionals.

>> No.69185610

That's fine and you sound like you're getting ready for your first internship with this bike shedding. Keep up the good spirit.

>> No.69185636

>Rule 1.3.a
>Braces shall always surround the blocks of code (a.k.a., compound statements), following if, else, switch, while, do, and for statements; single statements and empty statements following these keywords shall also always be surrounded by braces.

If apple followed this, then this site:


would not exist, you greasy knob.

>> No.69185650

Meh it quickly got fixed and no real damage was done.

>> No.69185656

For me it's pointers in c because I'm a Web dev and I'm too brainlete to do it someone help

>> No.69185678

I don't see how you can fail to understand pointers, reference semantics with mutability like python is harder to grok

>> No.69185706
File: 135 KB, 800x668, 1540168794643.png [View same] [iqdb] [saucenao] [google] [report]

>In my world, easily preventable bugs that cause massive disturbance on critical platforms, wasting tens of thousands of hours of programmers world wide, are okay if they are fixed "quickly", you know, no more than a year at most.

>> No.69185720

Yeah, give or take. The time they spent not sperging over syntax, they spent fixing other bugs that never came to be.

>> No.69185728

Yeah you eventually get to the point where you suprise yourself and say,

>Oh damn! Thank god pointers exist, or else this would be really fucking hard.

>> No.69185780

>Thank god pointers exist, or else this would be really fucking hard.
Where by this I mean crashing this app with no survivors.

>> No.69185829
File: 448 KB, 629x454, 1537410441573.png [View same] [iqdb] [saucenao] [google] [report]

Right, because this code takes no time at all to read:

void foo()
if (reddit)

for (int i=0; i<m_PenisLength; i++)
if (finished)

>> No.69185840
File: 381 KB, 440x430, 1512119352916.png [View same] [iqdb] [saucenao] [google] [report]


>> No.69185855


>> No.69186097

80 column, 8 space fags should be shot.

>> No.69186116

I inherited code with exactly this formatting style (except for the empty conditionals were just completely commented out; lots of commented out code everywhere). Thank Jobs for clang-format. Of course I'm unnaturally attached to
if (this_thing_is_true) a = 12;
else if (this_other_thing_is_true) a = 13;
else a = 14;

for simple conditionals, so I'm going to be someone else's headache someday.

>> No.69186169

Try to implement a void function that takes a linked list, removes the desired element. Make sure it can remove the first element.

>> No.69186199

[] operator commutativity in C/C++
arr[i] == i[arr]

>> No.69186214

I let my IEDs refactorer take care of re-indenting.

>> No.69186624

Why do you have IEDs? Are you a terrorist?

>> No.69186802

I was confused as well.

Regardless, his comment is still stupid. Commenting out that line has nothing to do with indentation. What the person was getting at was if it was commented out, the if statement then applies to the next line right after it; an easy mistake for any programmer to make.

>> No.69186839

I would love to see code where that's a sane usage.

>> No.69186939

Compilers also have warnings for this. And cppcheck should catch it as well. Yes this is one of those "if you just do this small thing then you will make the issue many times more difficult to trigger" but I honestly think that the problem in this scenario is so insignificant and rare that it just doesn't make sense to bother if and at this point just becomes a matter of preference.
At the end of the day, this happens with lots of random bugs. People say: "well this wouldn't have been a problem if you just programmed like I always programmed" and it's always over some random one-off dumb bug which should have been spotted a mile off.

>> No.69186948
File: 149 KB, 500x522, 1540950900271.png [View same] [iqdb] [saucenao] [google] [report]

>thank jobs for clang-format
What does this mean?

>> No.69187188

Probably that apple is a sponsor of the llvm project.
But their involvement is often overstated compared to other organizations.

>> No.69187270

asm doesn't have this problem

>> No.69187288
File: 69 KB, 637x504, 1546512176995.jpg [View same] [iqdb] [saucenao] [google] [report]

>Compilers also have warnings for this. And cppcheck should catch it as well. Yes this is one of those "if you just do this small thing then you will make the issue many times more difficult to trigger" but I honestly think that the problem in this scenario is so insignificant and rare that it just doesn't make sense to bother if and at this point just becomes a matter of preference.

You are wrong. Say you need to debug the conditional; unless you have a macro/template you can wrap the statement in, you are going to need to add a debug line by itself, neccessitating a pair of curly braces.

That and you want consistency across your code, making "ALWAYS HAVE BRACES" a simple rule to follow.

Furthermore, definitions and arbitrary blocks should always be linebreaked, where as conditionals and loops should be proceeded with an immediate brace, like so:
void foo()
QString s(m_GentooIsRice);
// Sanitize String for fud
s.chop(s.indexOf(" "));
forever {
if (bar) {
} else if(tub) {
} else {
out: // mmmm a practice I plan to adopt

This adds context telling users what the scope of certain lines of code are restricted to, making it easier to immediately grasp on first glance. It also folds the code nicely.

>> No.69187545

Not really niche but I'm currently learning C and like this pattern for generics:
typedef enum
} MyStructType;

typedef struct
char name[32];
MyStructType type;
} MyStructTypeHeader;

typedef struct
MyStructTypeHeader head;
float value;
} MyStructFloat;

typedef struct
MyStructTypeHeader head;
uint16_t value;
} MyStructUint16_t;

void my_set_value(void* t, double value)
MyStructTypeHeader* h = (MyStructTypeHeader*) t;

if (h->type == MST_UINT16_T)
((MyStructUint16_t*) h)->value = (uint16_t) value;

if (h->type == MST_FLOAT)
((MyStructFloat*) h)->value = (float) value;

>> No.69187586

typedef'ing enum is truly niche

>> No.69187672

Also I like to challenge whoever is next in line working with my code by substituting for loops where I don't need the index with a simple pointer loop:
int main(void)
uint8_t* p;
p = malloc(10 * sizeof *p);
for (void* end = &p[10]; p != end; ++p)
*p = 1;

return 0;

>> No.69187732

Just use tab, then adjust the editor to show how many spaces you want.

>> No.69187737

That's not what's neat about this snippet.
The trick is using a common header (which has offset 0) to check for the specific type.
Probably nothing special to the experienced C programmer but it's more than just typedefing an enum.

>> No.69187739

>unions niche
What... what am I reading? I thought this board loved C. Union is used everywhere.

>> No.69187750

llvm originally used a modified gcc as its C/C++ compiler frontend. Apple hired the llvm creator to write clang because they wanted a compiler that a) had better compliation performance and lower memory requirements, b) was easily embedded for use in other parts of their toolchain, and c) was not GPLv3 infected.
Since then it's grown well beyond that, and Apple is now only one of many major stakeholders.

>> No.69187764

that is the problem, it is variable
you have to use spaces to make sure people don't fuck with your indents

>> No.69187767
File: 47 KB, 800x800, 1501762949312.jpg [View same] [iqdb] [saucenao] [google] [report]

if (false) {

>> No.69187790

>Probably nothing special to the experienced C programmer
yeah he would use a union

>> No.69187791

Ah yes the humble type object. I've made compile time automata with it.

>> No.69187988
File: 29 KB, 623x423, 1539627049131.jpg [View same] [iqdb] [saucenao] [google] [report]

switch (tableOfContents.split("\n").length()) {
case 0 ... 29:{chosenFontSize = QString::number(fontSizeMinimum+9); break;}
case 30 ... 34:{chosenFontSize = QString::number(fontSizeMinimum+8); break;}
case 35 ... 39:{chosenFontSize = QString::number(fontSizeMinimum+7); break;}
case 40 ... 44:{chosenFontSize = QString::number(fontSizeMinimum+6); break;}
case 45 ... 49:{chosenFontSize = QString::number(fontSizeMinimum+5); break;}
case 50 ... 54:{chosenFontSize = QString::number(fontSizeMinimum+4); break;}
case 55 ... 59:{chosenFontSize = QString::number(fontSizeMinimum+3); break;}
case 60 ... 64:{chosenFontSize = QString::number(fontSizeMinimum+2); break;}
case 65 ... 69:{chosenFontSize = QString::number(fontSizeMinimum+1); break;}
default: {chosenFontSize = QString::number(fontSizeMinimum+0); break;}

btfo clang

>> No.69188051

fontSizeMinimum+9 - (L - 29 + 4) / 5

>> No.69188062

If some of the variants are large (or there are many of them and a slight difference in size would matter) and you want to point to the object payload directly, then a header like this is great. Just be sure to respect alignment.

>> No.69188126

Python has a 'with' feature which is basically the same as taking the returned output of a method and passing it to another. It is super stupid because only handles one functions output to one functions input, when if you do it the right way there are no limits. It caters to brainlets. You know the type: "let's learn codes!"

>> No.69188134

This is why sepplesfags shouldn't be allowed to write C. They ruin it with typedefs, camel case, and casting everywhere (in many places completely unnecessarily).
And then writing shit like "void* t".

>> No.69188139
File: 74 KB, 960x926, 1510855067341.jpg [View same] [iqdb] [saucenao] [google] [report]

I just wanted a god damn reason to use ranges

fuck off mom

>> No.69188181

I've used generators in conjunction with promises to display sequential animations. not the best use case but it kept the code nice and clean

>> No.69188637

Does it occupy 32 bits? I wouldn't be surprised if that thing does not works because of some padding or some other shit. I rather use masking.

>> No.69188712

Curious how you would do that example without a void pointer / casting.

>> No.69188816

float is conventionally a 32-bit single precision ieee float but it could be anything.

>> No.69189326

Let's start off with fixing that mess:
enum type {

struct gen {
char name[32];
enum type type;

struct gen_int {
struct gen head;
int value;

struct gen_float {
struct gen head;
float value;

void set(void *t, double value)
struct gen *h = t;

switch (h->type) {
case T_INT:
((struct gen_int *)h)->value = value;
case T_FLOAT:
((struct gen_float *)h)->value = value;

Now let's consider this for a moment. Still is ugly (requires casting). How about trying to just write your program in a way which doesn't require such a stupid high-level concept in a lower level language which has no clean way of implementing precisely this kind of weird "OOP"-esque crap?
Let's just consider an alternative union based approach:
struct gen {
char name[32];
enum { T_INT, T_FLOAT } type;
union {
int i;
float f;

void set(struct gen *g, double value)
switch (g->type) {
case T_INT: g->i = value; break;
case T_FLOAT: g->f = value; break;

Aaaaah... Much less ugly looking. And given a complete lack of context on what the intention of the original code, no less functional.

>> No.69189443

Of course, I was not talking about the float. I was talking about the structure.
I don't know if bitfields are required to use exactly the number of bits you specify and I'm mostly unsure if any of those fields are required to be stored compactly (with no padding in between).

>> No.69189474

The layout of bitfields are implementation defined. However if you check your platform's ABI almost all of them will implement bitfields so this works.

>> No.69189485

meanwhile in sepples
struct Gen
char name[32];
std::variant<int, float> v;

void set(Gen *gen, double value)
visit(gen->v, [](auto &v){ v = value; });

>> No.69189518

Which looks ugly as fuck, requires reading 10 books on the fucking language and makes no sense to anyone who might be reading it casually coming from any other language.
With the amount of random fucking shit going on here I can't even begin to imagine what is going on here, and I the last C++ standard I tried to bother with was only C++11.
Well done C++, you've succeeded in having more features than I have hairs on my head.

>> No.69189548

you're basically retarded if you don't understand that code. Sorry pal.

>> No.69189588

>poo in street forever regardless if OP is gay or not

>> No.69189632

>C++ is bad because it has too many features
imagine being this retarded

>> No.69189648

Not him but orthogonal features are a bad thing. It makes it harder to understand what code does when there are more things it could mean. A small but powerful set of tools is better than a large but cluttered one.
However, a large cluttered toolset is still better than one which is outright deficient like C.

>> No.69189673

Thank you. It might be actually useful in the future, even if I still think masking is a just as fast and safer option for most of the times.

>> No.69189694

>not knowing what orthogonal means

>> No.69189727

You flipped your visit arguments around

>> No.69189740

Depends on one's definition of niche but I really like properties in c#. I also like ref and out.

>> No.69189743

It doesn't mean the same thing as complementary.

And also forgot to make my lambda capture. D'oh.

>> No.69190761

Worked as an embedded developer for 2 years on a legacy system. I probably saw 3 unions in the entire code base and added 1 myself in that time.
I have a hard time believing they are used everywhere. More like they are used for a few purposes when dealing with bitwise operations, hence niche.

>> No.69190984

Make three concrete examples. And don't borrow any of them from this thread.

>> No.69191020

Or maybe C++ just has such feature bloat that it's unreasonable for anyone who doesn't dedicate months of solid work into it to be able to even understand some other person's random combination of 5 features without reading up on them?
Yes, correct. Having a language which tries to implement every feature is like trying to be someone who specialises in every subject of mathematics at once. The end result is just shit all round. Worst of all, nobody can understand anybody's code because everyone uses some unfamiliar subset of the language.
I think you're outright deficient if you think C is "outright deficient" of features.
The feature-set of C is perfect for what I need it for.
The feature-set of C++ is on the other hand useless for me. Since there are better languages than C++ which can be used in the areas where I might want to use a language other than C.

>> No.69191245

The features used there are basic as hell, though. What's supposed to be confusing? The presence of a class template? The presence of a function template? A lambda? All of that shit's in C++11.

>> No.69191246

actually pretty cool, thanks

>> No.69191316

I stopped learning C++11 once I realised that it was going to take months and I would get nothing out of it in the end. I had thought that was a lambda but you couldn't tell because it doesn't follow any lambda syntax I've ever seen any language have. So who knows.
Same with visit, what is it, how does that work with this variant type?
Just the fact that the language has that many features but it's unreadable because they're hidden behind poorly named types and functions is one problem.
At least with ada you could read similar code to this without much experience with it.

>> No.69191320

You sound like a lazy, incompetent coder. Step up your game.

>> No.69191339

It's sad to see somewhat intelligent people hit their programming ceiling so early in their lives due to the Caveman programming language.

>> No.69191375

You're basically just bitching that you don't automatically understand a library you haven't seen before. Peak brainletism.

>> No.69191406

No thanks, I have better things to do than to learn a useless dead language.
I put my time into learning much more interesting languages like ada2012, erlang, scheme, lua, python and fuck knows if I remember what else.
Those languages, although not perfect, are at least usable, unlike shit like C++.
It's not like C++ has unique features I'm missing out on by not knowing how to use. I merely refuse to bother learning C++'s poorly thought out way of presenting those features in 100s of various subtly different ways and then layering dozens of shitty hacks over all of that to make those features work better in a language which should never have tried to implement them.
no, friend, this stupid shit is part of the language.
C++ is the new perl. Making it much easier to write almost indecipherable code faster.

>> No.69191424

>no, friend, this stupid shit is part of the language.
...in the standard library, dumbass.

>> No.69191449

which is ... part of the language

>> No.69191465

and anyway, lambdas and the retarded <> notation ARE part of the language proper

>> No.69191475

It's not a feature of the language. Knowing and learning all the constructs a language offers is not the same as knowing and learning every function you could possibly import.

I can't tell, are you or aren't you complaining that templates and lambdas are too hard for you to grok?

>> No.69191515

>random combination of 5 features without reading up on them?
Let's see
Structs you know.
std::variant is an algebraic type, a union. Very famous in modern (1960s+) languages.
Then you have the default language-wide syntax of a lambda function, an in-place definition of a method. All modern languages have lamdas.
I have a better things to do than unwinding the cryptic knots of a C program which its own owner wouldn't recognise in a month.
>interesting languages
C is turing complete, you can do anything with external libraries. You needn't learn other languages. Well, maybe C++ because of the amazing std library and sensible syntax.
>unique features
Runtime zero-overhead (vtables fit in modern CPU registers, dab on em folks) polymorphism. Compile-time zero-COST ad-hoc polymorphism through templates (impossible in C due to the beyond dogshit linker).

Dude I literally spent a summer break watching cppcons and reading guidelines. I read A Tour Of C++ the morning before acing my OOP exam.
It's okay if you make shitty unix applets, but you are flipping the bird hard at people reading your cryptic ass nigger code.

>> No.69191528

>It's not a feature of the language
sepplesfags redefining what a standard is
if it's in the standard (which it is) it's part of the language
go back to C#
>I can't tell, are you or aren't you complaining that templates and lambdas are too hard for you to grok?
Template syntax just looks ugly and the whole way in which it's used in C++ is a disaster. Ada did this better.
Lambdas are not hard to grok, it's just C++ goes out of its way to make it absolutely unclear what the fuck they are without reading the documentation on them

>> No.69191529

No! The standard library is up to people to implement themselves. ISO C++ has no word in how std::string or std::vector are created, for instance. And libstdc++ and libc++ have different short string optimisations.

>> No.69191557

The entire language is up to vendors to implement themselves, ISO just decides on the specification.
So what is your point?

>> No.69191590

Still haven't explained how visit fits into this.
I know what a lambda is and what a variant is. But in C++ you wouldn't be able to tell something was a lambda without someone telling you, the syntax is that retarded. And with this "visit" shit there's no clear idea of how this variant type is meant to be used.
>I have a better things to do than unwinding the cryptic knots of a C program which its own owner wouldn't recognise in a month.
Don't blame me for the retarded C ramblings of C++ programmers pretending they know how to write C.
>Well, maybe C++ because of the amazing std library
A standard library which is basically worthless.
>sensible syntax
This is not even bait at this point.
>Runtime zero-overhead (vtables fit in modern CPU registers, dab on em folks) polymorphism.
Nobody gives a shit about polymorphism. It's like saying that your language has a unique and fast way of wiping your arse, but I don't need a programming language to wipe my arse.
>You needn't learn other languages.
Yes, unless I want to be able to read my code, or better yet, want other people to read my code, or better yet, want my code to be debug-gable by mere mortals.
>Compile-time zero-COST ad-hoc polymorphism through templates (impossible in C due to the beyond dogshit linker).
C++ templates are the same kind of talking point as those shitty 90s RAD languages.
C++ templates are a disaster which should be aborted and re-designed from scratch by someone with at least one third of a brain.
>Dude I literally spent a summer break watching cppcons and reading guidelines. I read A Tour Of C++ the morning before acing my OOP exam.
The fact that you're proud of acing an "OOP" exam proves to me that your opinion of C++ is completely worthless to me personally.
How about acing something useful like an exam on an area of mathematics?
>It's okay if you make shitty unix applets, but you are flipping the bird hard at people reading your cryptic ass nigger code.
My code is pristine.

>> No.69191603

Well it's not part of the language. It's just other people's code. I can literally decide short strings are now 32 bytes and make my own standard containers (as facebook does).
I mean, you just have to get the philosophy behind C++ and that's "reuse, reuse, reuse". C++ is a lightweight transparent language based on zero-overhead abstractions. If you see how some STL algorithms are implemented, you've seen them all.
At most, you may look up cppreference to remind yourself but I wrote an extension for VSCode for my company that just integrates cppreference results as an extra taskbar alongside intelllisense. Tell me I'm not good.

>> No.69191685

>muh syntax
baby duck syndrome at its finest

>> No.69191737

>without someone telling you
Like what's so hard with lambdas? Any function takes arguments between round brackets () so it's expected that taking capture variables instead goes in another type of brackets. Curly ones are for code so [] will do.
I'm a good programmer because I can decide whether a piece of code does what it's meant to do. With C, you are hiding your intentions behind pages of syntax that has zero worth regarding algorithms. C is bad.
>basically worthless
Literally puts ad-hoc C wheel reinventions to shame.
Certain algorithms and pseudocode call for algebraic or runtime types. C can't do that properly, so you're stuck implementing the algorithm wrong.
THat's not even a word at this point. C++ is easily more debug-gable than C because you can simply skip over half the code of half the functions. RAII and other static analysis destroys entire domains of bugs and errors. That means debugging is effectively O(logn) due to Divide and Conquer.
>a disaster
Hmm, no they work perfectly. Granted, not everyone writes perfect forwarding, but not everyone needs or should write perfect forwarding. Still, C++17 brings argument type deduction, so no more make_unique or make_pair or crap like that.
Lol? It's assumed I ace my mathematics (and I do). I assume everyone here aces their mathematics and that programming is hard because people spend the least time on it.
>my code is pristine
No, your code is 10% meaning and 90% language keywords and constructs.

>> No.69191823

Fuck me.
Are you literally retarded?
The implementation is not important. The whole idea of a spec is that people implement it. That as >>69191557 said means the standard library AND the language proper. The entire thing is up to the implementer's whims and decisions. That mean's that regardless of the implementation, std::string must act as specified or else the implementation is non-conforming.
Sepplesfags wouldn't understand this because despite their language demanding a thorough grounding in its standard to be able to navigate tricky areas, they feel like they can just pretend to know those parts until not knowing them bites them in the ass.
No, your job achievements are not interesting anon, sorry.
If syntax is unimportant then surely with the amount of unicode-incorporated emoji now available you should advocate for all of C++'s functions and all remnants of the use of English be replaced with emoji.
I'm sure the language will become even clearer then.
>Curly ones are for code so [] will do.
>With C, you are hiding your intentions behind pages of syntax that has zero worth regarding algorithms.
>Certain algorithms and pseudocode call for algebraic or runtime types. C can't do that properly, so you're stuck implementing the algorithm wrong.
>No, your code is 10% meaning and 90% language keywords and constructs.
Literally what?
Have you ever written C?
Did you actually learn C outside of your dumb professor failing to teach you it?
Are you baiting?
>That means debugging is effectively O(logn) due to Divide and Conquer.
Except wait a minute, gdb is perfectly capable for debugging C and I reach for it only once a year but a C++ programmer cries when they can't use Visual Studio.
Then there's the sheer amount of memory leaks I see C++ programmers produce.
>RAII and other static analysis
Do you even know C++ at this point. Because even I know that RAII is not static analysis.
Fuck this, I'm going to hit the hay. Go bait someone else

>> No.69191842


>> No.69191948

>std::string must act as specified
You're desperately trying to act smart but it's not working out for you at this point.
>AND the language proper
You mean the compiler? Like I can't mix and match?
>tricky areas
There are no tricky areas in C++ as long as you follow your company's static analysis tools and guidelines.
>Have you ever written C?
Sure have, helped incorporate google store in a select few automobiles.
>memory leaks
Never seen or heard of memory leaks in C++. Perhaps there are people who don't use IDE's that spot such bugs 25ms after you write them, but they're more people like you.
I mean, after all, manual memory management is a leftover from C days.
>RAII is not static analysis
Hmm even if you were to google this topic, you'd come across the GSL, which contains std::owner<>, which tracks the transfer of heap allocated objects throughout your code and *is* statically analysable. I use it and my coworkers use it.
Fucking watch a cppcon or two so you can actually make convincing arguments against C++, it's not '98 anymore. Bye

>> No.69191976

Yikes, that's actually gsl::owner

>> No.69192371 [DELETED] 

java methods

>> No.69192429

In C, this:
void func();

Is not a function that takes zero arguments, but is a function that takes an unknown amount of arguments. It is neat when you don't care to specify the arguments in the declaration, or can't for other reasons. An example is a function that perhaps takes a mode and does a switch on that mode, and depending on that mode, expects the arguments to be something else. The syscalls on Linux are an example of this.

>> No.69192517

But you have no way to retrieve the arguments, except using assembly instructions. You should use a variadic function in that case.

>> No.69192653

>But you have no way to retrieve the arguments

This is contrived, but whatever.
void sample()
int a, b;

a = 10;
b = 20;

/* swap */
func(SWAP, &a, &b);

/* replace a and b with 30 if they are equal to eachother */
func(REPLACE, &a, &b, 30);

static void func_swap(int *first, int *second)
int tmp = *first;

*first = *second;
*second = tmp;

static void func_replace_eq(int *first, int *second, int newval)
if (*first == *second) {
*first = newval;
*second = newval;

int func(int mode, long arg1, long arg2, long arg3)
switch (mode) {
case SWAP:
func_swap((int *) arg1, (int *) arg2);
func_replace_eq((int *) arg1, (int *) arg2, int
return 0;

return 1;

>> No.69192928

Yet, none of your func* family has the signature of a function with unspecified number of arguments. What you did could have been done with a variadic func().

>> No.69192966

It is totally possible to have all that int func(int mode, long arg1, long arg2, long arg3) { ... } in the .c file and int func(); in the .h file

>> No.69192973

Thanks, that is a lot more elegant.
Now I actually learned something about progamming on /g/, who would've thought

(One question about the final version: doesn't the union reserve as much space as the max sizeof type in it?
When using a struct array of generic types that are vastely different in size, it could make sense to use two separate structs.)

>> No.69194718

Why do C people hate namespaces? I really don't understand this

>> No.69195104

Because C doesn't have them

>> No.69195111


>> No.69195119

that's just how it be

Name (leave empty)
Comment (leave empty)
Password [?]Password used for file deletion.