[Boards: 3 / a / aco / adv / an / asp / b / bant / biz / c / can / cgl / ck / cm / co / cock / d / diy / e / fa / fap / fit / fitlit / g / gd / gif / h / hc / his / hm / hr / i / ic / int / jp / k / lgbt / lit / m / mlp / mlpol / mo / mtv / mu / n / news / o / out / outsoc / p / po / pol / qa / qst / r / r9k / s / s4s / sci / soc / sp / spa / t / tg / toy / trash / trv / tv / u / v / vg / vint / vip / vp / vr / w / wg / wsg / wsr / x / y ] [Search | Free Show | Home]

/dpt/ - Daily Programming Thread

This is a blue board which means that it's for everybody (Safe For Work content only). If you see any adult content, please report it.

Thread replies: 322
Thread images: 34

File: c.png (95KB, 557x720px) Image search: [Google]
c.png
95KB, 557x720px
Old Thread: >>61649395

What are you working on, /g/?
>CIA nigger monkey's want to know.
>>
>>61656611
>>
File: monads.png (797KB, 793x670px) Image search: [Google]
monads.png
797KB, 793x670px
the monad as interpreted by functional programmers is the ultimate embedding of imperative programming within functional programming and represents the pinnacle of 20th century programming innovation, uniting imperative programming, type theory, category theory, first class functions, custom data types, procedural and imperative concepts along with continuations and the lambda calculus to perfect the concept of the pure typed programming language. it is the cherry on top of the proof within the pudding that functional programming is strictly superior to imperative programming.

philistine memesters need not reply
>>
>>61656645
>when functional programming is so useless they have to embed imperative programming into functional programming to get anything done
>>
File: 1490574698149.jpg (23KB, 200x250px) Image search: [Google]
1490574698149.jpg
23KB, 200x250px
>>61656614
>yfw you need modules for the headers you need to head the modules for the source header module templates but you forgot to importclude the moduleheader's sourcelink
>>
>>61656662
>future state of C pee pee
>>
>>61656725
surely you mean c+=
>>
>>61656725
>>61656739
++C
>>
>>61656757
Loading is patriarchal oppression
>>
>>61656757
https://github.com/ErisBlastar/cplusequality
>>
File: 1465344167068.jpg (19KB, 640x360px) Image search: [Google]
1465344167068.jpg
19KB, 640x360px
Jesus Cringe
https://www.youtube.com/watch?v=Ci48kqp11F8
>>
>>>/lgbt/8650537
>>
>>61656725

You don't know what a meme is, do you.
>>
How am I supposed to do floating point operations if shit like this keeps happening?
0.1 + 0.2 == 0.3
>>
>>61656792
stop using ==
>>
>>61656796
How do I do it then? It always returns false.
>>
>>61656792
Use a threshold value.
>>
>>61656805
use >=
>>
File: tad2.png (592KB, 1175x687px) Image search: [Google]
tad2.png
592KB, 1175x687px
>>61656789
>>
>>61656792
(0.1 + 0.2) - 0.3 < epsilon
>>
>>61656792

You should probably get a book or website to educate yourself in how floating point numbers actually work and you'll finally understand why your example (probably) won't work.
>>
In C I want a stack that will hold integers, a stack that will hold doubles and a stack that will hold strings.
I think I have to create 3 different structs and different pop(), push() methods for each.

How should I name them?
struct stack_i { .. };
int pop_i(struct stack_i *s);

struct stack_d { ... };
double pop_d(struck stack_d *s);
>>
>>61656821
You need to double bound it to approximate ==.
Which isn't a problem in real situations because measurement is never accurate.
>but I wanted to use fp to track a execution path through my program
Misguided, use an int or flag through a bit field.
>>
>>61656940
Use a macro to generate code for each, or void* to make it somewhat generic.
>>
>>61656940
It's a shame C doesn't have generics.
>>
File: pondering-retard.jpg (23KB, 550x421px) Image search: [Google]
pondering-retard.jpg
23KB, 550x421px
I'm trying to get my head around references in C++.

Suppose I have this function,
void get_size(int &width, int &height)
{
width = W; //W is defined as 16
height = H; //H is defined as 9
}


and I have this main:
int main {
//initialise two variables here, w and h
//I want w and h to be references to W and H

get_size(w, h);

return 0;
}


How do I initialise w and h?
>>
>>61656940
switch to C++ and use templates.
>>
>>61656995
int& w = W;
int& h = H;

or just use W and H
>>
>>61656954
Macros are a good idea, but I don't think I will be able to deal with them.
If I use void* how I will deal with malloc() without knowing the size? Won't this make it very complicated?

Could you please give me a link to a good example or some good naming conventions or an example with macros?
Everything I find online are terrible examples with data structured stored on the stack, without malloc() and with global variables.

>>61656956
Even overloading functions and selecting the appropriate one with the argument and return type would be good.
>>
>>61656995
Just regular stack variables.
int w = 0;
int h = 0;
get_size(w, h);
>>
>>61656995
Do you know pointers yet?

>>61657038
C11 has a "generic" macro which is essentially function overloading.
>>
>>61657001
If I switch to C++ I could use basic data structures from the stdlib instead of reinventing everything.
I want to try C and see how far I can go with only the basic pointer and malloc()
>>
>>61656940
struct stack {
int type;
union {
int i;
double d;
};


// ({ }), statement expression supported by gcc, clang, tcc and maybe some others
#define stack_pop(stack_ptr) ({ \
... \
return_value; \
\ })
>>
>>61656940
https://raw.githubusercontent.com/nothings/stb/master/stb.h
Check out the dynamic array and hashmap here.
They're very convenient implementations
>>
>>61657052
>C11 has a "generic" macro which is essentially function overloading.
Wow, I didn't knew that, thanks, I'll look into it

Still I'd like to try and limit myself to simpler C
>>
If rewriting a stack is a significant amount of your time then your program sucks anon.
>>
>>61657049

Never mind, I'm retarded.
I tried this earlier and I made width and height unsigned because I thought to myself "these will never be negative, I might as well make them unsigned"
>>
>>61657070
I though about that but isn't using a union wasteful?

>>61657074
Thank you!
>>
>>61657106
What are the sizes of double, int and char* on your platform?
>>
>>61657106
It uses as much space as the biggest element in the union. The compiler might pad your struct anyways to something bigger so unless you are developing embedded system with like 4096k memory you shouldn't care about wasting 4 bytes.
>>
>>61656949

>You need to double bound it to approximate ==

No, you only need one bound. If the result is smaller than 0, it's automatically smaller than epsilon anyway. For example for epsilon = 0.1:

-0.00000000000000004  <  0.00000000000000004  <  epsilon
>>
>>61657089
I just want to make a calulator program, tokenize a string, use a stack to rewrite it in postfix notation using a stack while having the right operator precedence, then calculate the result using a stack.

Nothing fancy, I have already done in higher level languages, I just want to do it in plain C.

>>61657138
Good point, maybe I shouldn't care
It's that in C you are so low level that I'm constantly thinking that everything I do is wasteful and I can never focus to what I want to do
>>
>>61656995
>C# get set bullshit
lol use c u fucking nigger
>>
>>61657068
Nothing is stopping you from reinventing the wheel in C++, and templates are fucking convenient.
>>
File: 1391339708334.png (100KB, 242x234px) Image search: [Google]
1391339708334.png
100KB, 242x234px
>>61656614
>compiling an old project a work
>when building one module a following erorr comes up many times:
>"Warning. Use of 'auto_ptr' is deprecated"
>mfw
>>
>>61657320
that's a good thing anon
>>
>>61657320
search and replace auto_ptr for unique_ptr and add std::move wherever it refuses to compile
>>
>>61657349
Can you show us some examples of how true C++ autistes write fully move-aware code?
E.g. write a function that composes two other functions, so that
newFun = compose(f, g);
newFun(x) = f(g(x))
>>
>>61657454
new_fun = [=](int x){ return f(g(x)); };
Something like this? I can't see how you'd do it with lambdas, you'd have to do it with some weird functors.
>>
>>61657454
Why would you need move semantics for it?
#include <cstdio>

template <class F1, class F2>
auto compose(F1 &f1, F2 &f2)
{
return [&f1, &f2] (auto x) {
return f1(f2(x));
};
}

int p2(int v)
{
return v * v;
}

int p3(int v)
{
return v * v * v;
}

int main(int, const char **)
{
auto newFun = compose(p2, p3);
auto result = newFun(5);

std::printf("Result: %d\n", result);
return 0;
}
>>
>>61657562
>>61657578
I mean so that if each function is move-aware then the entire thing is move-aware

>>61657562
like this
[=](auto f, auto g){ return [&](auto x) { return f(g(x)); }; }

but works with rvalues and shit
>>
>>61657454
#include <cassert>
#include <utility>

template <typename F1, typename F2>
auto compose(F1 f1, F2 f2)
{
return [f = std::move(f1), h = std::move(f2)] (auto x) { return f(h(x)); };
}

int
main(int, char**)
{
auto result = compose(
[] (int x) { return x + 1; },
[] (int x) { return x * 2; }
);

assert(result(10) == 21);

return 0;
}
>>
>>61657624
>[f = std::move(f1), h = std::move(f2)]
Damn, I didn't know you could do that in a capture list. But shouldn't it be std::forward?
>>
>>61657633
They're interchangable in most contexts, std::forward is more verbose.
>>
>>61657624
I'm probably just over-thinking it.
Does this work if x in the lambda is rvalue?
I.e. is the composed-function universally referenced if the parameter functions are.

Would be nice if C++ provided this in STL, then you could compose functions and maintain semantics
>>
>>61656577
>What are you working on, /g/?
reading sicp
do I really need to watch the lectures as well? I watched the first one, but it doesn't seems do differ from the book
>>
>>61657645
template <typename F1, typename F2>
auto compose(F1&& f1, F2&& f2)
{
return [f = std::forward<F1>(f1), h = std::forward<F2>(f2)] (auto x) { return f(h(x)); };
}


It's been a while, and I forgot the difference, it's either the former or this version that is correct and respects move semantics.
>>
>>61657578
You actually can perfect forward to lambdas (at least I think that does it):
template <class F1, class F2>
auto compose(F1 &&f1, F2 &&f2)
{
return [f1 = std::forward<F1>(f1), f2 = std::forward<F2>(f2)] (auto x) {
return f1(f2(x));
};
}


However, why the hell would you want to do that is unknown to me. Move semantics is only needed when you write containers, which, really, is a whole art in itself.
>>
>>61657690
Some callable objects hold state, you don't want to copy that over and over again.
>>
>>61657690
>>61657700
Move semantics are magic to me, i'll probably never fully understand
>>
>>61657720
There's a certain moment where it just clicks. It's not that hard afterwards.
>>
>>61657728
I always get back to Effective Modern C++ if I need a refresher.
>>
>>61657720
Well, how I'll try to explain it to you how I explained it to one of my acquaintances.

Take a std::vector. It's basically a wrapper over a dynamic array. When you want to copy it, you create a new array and copy all the values.

However, there is one common case: what if you wouldn't use the original vector anymore? You'd still needlessly allocate memory and copy every element. That's where move semantics come in. Using move semantics, you can simply "steal" the data pointer from the original vector, leaving it with nothing. That way no data gets allocated or deleted dynamically.

Another common case is when you have a certain resource handle which you want to automatically free upon object's deletion (because, really, RAII is cool). If you want to pass it to object that lives longer than the original object's scope, you use move semantics. That way only one "true" object that owns the handle exist and you won't get fucky shit.
>>
>>61657645
>in STL
I actually hope there's gonna be STL2 somewhere down the line. I'm tired of writing .begin() and .end() everywhere.
>>
>>61657911
That is being worked on.
>>
>>61657911
>>61657922
I honestly don't think C++ can ever be a really good language. It would need to fundamentally and completely change.
>>
>>61657854
c doesn't use vectors
>>
>>61657934
It might get simplified syntax-wise, but there will always be milion ways of doing things.
>>
>>61657946
Good.
>>
>>61657946
That's not the problem though, there's still loads of poorly designed stuff, and backwards compatible stuff.
>>
C++11, i am trying to use a move constructor to zero a vector<bool>. There might be other ways but i am asking this to know if what am i doing is correct)


void clear() { data = vector<bool>(length, false);}



What i think it's happening: the newly created vector is moved into the old one, the memory allocated by the old one is free'd; abstractly when the temporary vector cease its existence a NULL pointer is freed since the temporary vector was moved in data.
The trade-off: shorter to write, a bit worse in performance since it involves an allocation and a deallocation.
>>
>>61657974
We don't talk about vector<bool>, Anon.
>>
>>61656577
on that book
>>
>>61657937
C doesn't has objects or move semantics or lambdas either (though I heard about a proposal for some sort of closures for the next revision of C).

>>61657934
C++ may not be a "good" language, but it's "good enough" for what I do (interfacing with both embedded devices through different means of communication and parts written in higher level language). Almsot all of the language's features (only std::vector<bool> and some shit with initializer lists are fucky) behave exactly like you would think, and using C++11/14 makes programming much less tedious than what you'd get with old C++ or C.
>>
>>61656577
>>
>>61658032
the one in the OP
>>
File: cianigger.png (81KB, 437x294px) Image search: [Google]
cianigger.png
81KB, 437x294px
>>61658042
>muh oop
wtf is a "OBJECT"
>>
>>61658061
Who are you quoting?
>>
>>61658061
Just a struct.
>>
>>61658061
DEPENDS HOW ABSTRACT YOU WANT TO GET ANON.
>>
>>61658074
>c++ is a horrible language
found the nigger monkey
white people use c
>>
File: oop 2.png (152KB, 1948x858px) Image search: [Google]
oop 2.png
152KB, 1948x858px
>>61658061
>>
>>61658080
>>61658084
so c++ is for niggers that can't into structs?
>>
>>61658053
Should I buy this book to really get into C++ and stop using it as Java?
Can I get it for free from somewhere?
Is attached picture any good?
>>
>>61658163
>buy
Pshh, anon. There's a thing. It's called
                                                                                                                                                                                                                                                                                                                   libgen.io
>>
>>61658163
Arguably the best book for a beginner. Don't go for Bjarne's shit.
>>
>>61658175
>.io
dumb faggot poster
>>
File: 1498966480903.png (87KB, 975x522px) Image search: [Google]
1498966480903.png
87KB, 975x522px
>>61658106
>>
>>61658181
>Don't go for Bjarne's shit.
>Proceeds to recommend C++
>>
>>61658186
What else should I use? gen.lib.rus.ec?
>>
>>61658210
Bjarne's books, twat.
>>
>>61658175
>Search for C++ Programming Language
>Only up to 3rd edition
What a shit site
>>
>>61658222
Oh, seeing the word ``shit`` I thought you meant C++
>>
>>61658232
There is a 4th, you blind faggot.
>>
>>61658163
>>61658053
>Actually wanting to maintain header files
Are you sick in the head?
>>
>>61658242
kek
>>
>>61658175
This is amazing!!! Thank You!!!
I feel like a veil has been lifted!
>>
What happened to akari-bbs?
>>
File: bjarne.png (38KB, 928x824px) Image search: [Google]
bjarne.png
38KB, 928x824px
>>61658243
Point me to it then, because all I get from searching the author goes up to the 3rd edition of the book.
>>
>>61658175
>tfw it's blocked in the uk
>>
>>61658300
Does Bjarne only work on C++ to profit from books?
>>
>>61658300
Sort by year my dude,
>>
>>61658305
that was his plan from the beginning
>>
>>61658305
Most of those are duplicates that differ in scans/file formats. There are only 4 editions of the book over 30 years.
>>
>>61658309
Fuck. I looked down at first before sorting by year and all I saw at a glance was that there was only one page, which led me to believe there were no more results. Turns out the two for the second page is halfway at the other side of the screen. Thanks and sorry for being a faggot.
>>
there is semen on your screen
>>
>>61658449
don't worry it's not my semen.
>>
>>61658524
>>
c++17 when. i need my if init statements already
>>
>>61658163
Reading it currently. It's alright. It's fucking huge though
>>
>>61658619
constexpr-if is the real deal
>>
Writing a Java VM compiler with higher-rank polymorphic concurrent dependently-typed STM Haskell vs. Go
>>
>>61658771
Did you finish that Markov Shitbot?
>>
File: hqdefault.jpg (23KB, 480x360px) Image search: [Google]
hqdefault.jpg
23KB, 480x360px
>>61658258
I'm just sick of Java telling me
>operator overloading, you don't need that
>>
>>61658871
Use C# then.
>>
>>61658871
haskell programmer here
I know how you feel
>>
>>61658871
>operator overloading
You should not be using that dumb fuck.
>>
>>61657164
Consider
1.0 + 2.0 == 3.0
(1.0 + 2.0) - 3.0 < epsilon //Intended to match the range 3.0+-epsilon, as stated
(1.0 + 3.0) - 3.0 < epsilon
1.0 < epsilon //Doesn't match, correctly.
(1.0 + 1.0) - 3.0 < epsilon
-1.0 < epsilon //1.0 + 1.0 - 3.0 =-1.0 and matches for any positive epsilon.
>>
>>61658924
>muh operator overloading hides a lot of what is happening
>>
File: gofessor.jpg (3KB, 75x100px) Image search: [Google]
gofessor.jpg
3KB, 75x100px
>>61658871
you love being told what to do. join us
>>
>>61658871
Wow Java doesn't have operator overloading but they have facilities that cause the diamond problem?
Silly.
>>
>>61658967
>We don't want multiple inheritance because we don't want the diamond problem
>btw we have multiple inheritance and the diamond problem now
Java was a mistake
>>
>>61658949
Not that anon but I'm writing in C++ and it's ridiculous. I tried using operator overloading on simple 4D vectors and my compiler decided to not inline the operator so it had me do a bunch of function calls for no reason.
It's pretty fucked. Now I need to use compiler specific attributes so my performance doesn't suck.
>>
>>61659002
You are compiling with -O3 right?
>>
>>61659008
Yes. It just happens when I'm deep inside a complicated callstack already so it's not that surprising the compiler barfs, but I would have thought that my simple operator overloads would be trivial to inline. Apparently not. Clang.
>>
>>61658949
>muh + should be able to leak memory and send all your key pressses to NSA
>>
Are most programming jobs dead-end hence the term code monkeys and the high rate of burn outs in the tech industry?

I'm an incoming freshman planning on majoring in CS and some of the stuff I hear about software industry scares me.
>>
>>61659049
leakMemory() + sendKeyPresses(NSA)


>this is valid C99
>>
>>61659049
literally anything keywords can do that thanks to macros
>>
>>61659069
#undef +

dumbfag
>>
>>61659002
>>61659008
>>61659027
What's worse is that it completely destroys any confidence I have in the compiler dealing with these abstractions. Now I have to inspect the ASM regularly to make sure it doesn't inline where I don't want it, and I have to profile both versions to see if it did the right thing or not. It makes it way harder to quickly make decisions because I know much less. Doing force inline everywhere is also a pitfall, but intuitively I suspect I have a decent feel for it.

Lots of additional manual work. I could only imagine the nightmare someone who cares about performance while using member functions, complicated templates and other crazy features would have to deal with.
>>
Is there any good statically typed language which has interpreter and compiler to native code?
>>
>>61659121
>to make sure it doesn't inline where I don't want it
to make sure it inlines where I want it to.
And realistically I shouldn't even care about what I want. What I should do is write a system that profiles the code with different inlining combinations.
>>
>>61659121
godbolt is handy if you frequently look at how things get optimized with several compilers.
>>
>>61659134
Haskell
>>
>>61659139
I don't use multiple compilers. I just need the one I use to work for me.
>web compiler explorer
Why? Why would anyone ever need that unless you're looking at silly toy examples and wish to show others?
>>
>>61659157
1 GB/s is not good
>>
>>61659134
>which has interpreter and compiler to native code
What do you mean?
>>
what are good projects on github for a beginner to contribute?
>>
>>61659182
It's not true either
>>
>>61659192
That there exists compiler that can compile native libraries/executables from the languages source code.
There should also exists interperter than interpret the languages source code.
>>
>>61659212
>native libraries/executables
What do you mean by this part?
>>
>>61659214
Executables or object files that conforms to the target operating systems ABI specifications.
>>
File: Memory Management - HaskellWiki.png (18KB, 755x137px) Image search: [Google]
Memory Management - HaskellWiki.png
18KB, 755x137px
>>61659198
I suspect this is clumsy wording. What they probably mean is that they do stack allocations that are cleaned up immediately by moving the stack pointer back. It's what you would expect of a functional language where you limit shared state.

Most don't really consider that part of the GC in imperative languages.
>>
File: attiny85.jpg (28KB, 620x264px) Image search: [Google]
attiny85.jpg
28KB, 620x264px
What's the best Linux distro to use in a WM if I wish to program a attiny85 with the arduino IDE and will only be doing that?
>>
>>61659284
A raspi would technically be fine.
>>
>>61659305
Not quite what I'm looking for anon. Unless you suggest raspbian as a VM OS. I kinda doubt you mean that.
>>61659284
>WM
VM. I mean.
>>
>>61657452
Then each network can fully focus on figuring out, "Is this a <number X>?".
>>
I'm confused with variable length arrays on C. As far as I understand, fixed length arrays allow the compiler to put in constant offsets in instructions, e.g., go 40 steps forward in stack after "int a[10];". However, with variable length arrays the jump offset would have to be read from memory, costing a memory fetch and a register.

Doesn't this make variable length arrays really slow compared to fixed length arrays? I guess they still are faster than heap allocation, but still doesn't seem very useful.
>>
>>61659529
>really slow compared to fixed length arrays
Nobody cares about performance.
Fetching the length of the array is smaller than making system call for allocating memory and with heap allocation you would still fetch the length from memory.
>>
File: tumblr_mfpfpr5jRF1qfn715o1_1280.jpg (61KB, 800x600px) Image search: [Google]
tumblr_mfpfpr5jRF1qfn715o1_1280.jpg
61KB, 800x600px
I have a problem with this binary subtraction.

1100 - 1000

I'm testing to see whether all subtraction problems can be solved by converting the negative number to Two's Complement form and then just doing addition. This subtraction seems to prove that I can't.

If I convert 1000 to it's Two's Complement form, I get:
0111 + 1 => 1000

It's the same number. Am I doing something wrong, or have I just discovered the limits of a Two's Complement approach to subtraction?
>>
>>61659529
It's marginal. You should prefer static arrays over VLAs where sensible (mainly for simplicity purposes frankly) and VLAs over heap allocated arrays.
>>61659571
Misleading. Most likely you have a half decent allocator that doesn't do system calls for every allocation. But yes VLAs faster than heap allocated arrays.
>>
>>61659626
With 4 bits and 2s complement, the variable can hold values -8..7. The negation of -8 (0b1000) is not in this set, so there is no well-defined expected behaviour. The negation of -8 is -8, so that the operation is a bijection.

Nonetheless, the end result of the addition should match after overflow. You have:
1100 - 1000 = 1100 + 1000 = 0100
(-4) - (-8) = 4 = 0b0100
>>
>>61659750
Which method would you regard as superior for binary subtraction: borrowing or conversion to Two's Complement?

Two's Complement feels more elegant to me, because you don't have to fuck around with all the moving of values to columns, but this example is a little awkward.
>>
File: 1491824817544.png (50KB, 1349x684px) Image search: [Google]
1491824817544.png
50KB, 1349x684px
>tfw pic related compiles and works as intended with
 gcc -Wall -Wextra -pedantic-errors -O3 -std=c89
>>
>>61659808
also
-Werror
!
>>
>>61659808
void inline(restrict) void *const restrict;


Wtf?
>>
>>61659808
>>61659837
-Wjust-fuck-my-shit-up=senpai
>>
>>61659849
Fun with keywords defined in later standards.
>>
>>61659849
It's the old-fashioned declaration that means
void inline(void *const restrict)
>>
>>61659859
GCC also accepts =+ and the likes for the sake of compatibility with really old code.
>>
>>61659808
This is horrifying.
>>
>>61659907
Oh right, I forgot about that, it makes sense now.
>>
File: 1479941619600.png (1MB, 1334x750px) Image search: [Google]
1479941619600.png
1MB, 1334x750px
>>61659808
>
-std=c89
>>
>>61659911
=+? What's that supposed to do?
>>
>>61659976
Same thing as +=.
>>
>>61659976
the same as += maybe?
>>
>>61658948

Oh yeah, I get your point now.

I thought we were talking about known values, but if we talk about variables than you have to use two bounds, right.
>>
>>61659990
When has it ever been effected? a=+b should mean
a = (+b)
, even though there's no use for it, no?
>>
This program:
#include <stdio.h>

int main(void)
{
const float q = 3.0 / 7.0;
const float r = 3.0f / 7.0f;

fputs("Case 1: Using doubles\n", stdout);
if (q == 3.0 / 7.0)
fputs("Equal\n", stdout);
else
fputs("Not equal\n", stdout);

fputs("Case 2: Using floats\n", stdout);
if (r == 3.0f / 7.0f)
fputs("Equal\n", stdout);
else
fputs("Not equal\n", stdout);

return 0;
}

Produces the following output:
Case 1: Using doubles
Not equal
Case 2: Using floats
Equal


Really makes you think.
>>
>>61660102
>const float q = 3.0 / 7.0
>>
>>61660102
>checking equality on floating point numbers
>>
>>61660102
Boils down to
double x = 3.0/7.0;
assert (((double)(float)x) != x);


Downcast-upcast fucks shit up. Annoying, but not that unexpected imho.
>>
>>61660102
Doubles are better than floats.
What's the problem?
>>
>>61660102
when will the checking for float equality meme die?
>>
>>61660102
What does it make you think?
>>
Reminder to always give useful names

>float f
>string s
>int i
>double d
>>
>>61660175
That floats are useless.
>>
>>61660183
>int i
Terrible.
>>
>>61660140
What else can I do? Something like
#define PRECISION (1e-10)
#define flt_equal(a, b) \
(abs((a) / (b)) - 1 < PRECISION)


>>61660175
That I shouldn't store double constants in floats.
>>
>>61660155
Nah mate it's the opposite. Reread it.
>>
>>61660187
What do you call your ints?
>>
>>61660187
int n is better.
>>
>>61660213
i, j, k make good indices
n, m make good sizes
>>
File: 1467019345752.jpg (10KB, 180x157px) Image search: [Google]
1467019345752.jpg
10KB, 180x157px
>>61660213
>int n
>n
>>
>>61660161
People just need to
-Weverything and it's sorted.
>>61660203
But you're comparing float to double. It should be wrong because floats have worse precision than double. Make q and r double and you will see the problem.
>>
>>61660221
this.
This is why
>>61660204
I always have some context that guides it but if I were to just declare some integer without context it'd be something like foo/bar/baz/foofoo/foobar/foobaz, to make it explicit that there's no context considered.
>what if you have more than 6 contextless variables
I delete the program and start over.
>>
>>61660284
What if foo has contextual meaning?
>>
>>61660312
I guess I just fire whoever made it so.
>>
>>61660328
Can you fire your boss who is also your mother and yourself?
>>
>>61660346
How dare you suggest my mother would do something like that?
>>
>>61660357
Don't talk back to your mother like that
>>
File: Untitled.png (155KB, 3531x2726px) Image search: [Google]
Untitled.png
155KB, 3531x2726px
>>61656577
I'm actually trying to learn C using precisely the text in the op pic. Everything was going great until I got to the character input/output in the tutorial (p.16, also in pic).

I guess I mostly just don't understand why we use the int type for the character c. I understand why we can, but their explanation as to why doesn't make sense to me.

They say "we must declare c to be a type big enough to hold any value that getchar returns. We can't use char since c must be big enough to hold EOF in addition to any possible char."

I thought getchar only returns one character. So why must c be large enough to hold any character + EOF?

Any help would be tremendously appreciated. I have read this section dozens of times and still can't make any progress.
>>
>>61660426
Lets say there are 256 different kinds of characters. A char would be 8 bits and one byte long and it would be able to hold all those possibilities.
getchar must be able to return the character if there is one, or a special EOF value that indicates that you have reached the end of the file and there are no more chars. That means you now have to represent 257 values. That can't fit in a single char.
>>
>>61660426
Say there are n possible char values and any of them can be in the file. To signal EOF, you need a value that's distinct from all n others. You need n+1 distinct values, and char can only represent n of them by definition. Thus you need a bigger type than char. QED.
>>
>>61660227
Yes, n. You know, like in math.
>>
>>61660595
Excuse me, but "n" is an inferior choice of letter
>>
>>61660257
>People just need to
>-Weverything and it's sorted.
This doesn't warn about checking for floating-point equality.
>>
>>61660426
>I thought getchar only returns one character. So why must c be large enough to hold any character + EOF?
getchar must also return a special value to indicate that there is nothing more to read, this value, called EOF (end of file), does not fit in a char type, or else it would be a valid character returne from the input. That's why the return type is int.
>>
File: pypy.png (85KB, 268x448px) Image search: [Google]
pypy.png
85KB, 268x448px
Hey friends,

Is it acceptable to build a queue of pointers/ references instead of the objects/ values themselves?

I'm only beginning with C after a long time of using Python.

Say I have a multi process program and I'm sharing data between processes via queues. I've now written function that needs to track the state of the individual items in the queue reguardless or their position in the queue.

I've hit this problem in python and could not solve it (without completely changing the implementation)

But I came to the conclusion that had I been able to add pointers to the queue, rather than the whole "objects" this wouldn't have been a problem.

Just trying to sanity check my thinking, plz no bully
>>
File: 1468882928057.png (199KB, 439x392px) Image search: [Google]
1468882928057.png
199KB, 439x392px
Employed Haskell programmer reporting in
>>
>>61660640
objects are reference types in python tho
>>
After all those talks about "startup bro culture cults" I kinda want to work for one desu. Hang out with my codebros, get high on cocaine and redbull, hit on bitchez drunk at our workplace and make 6 figures per year. I mean I love my mates but they are kinda boring shutins with singleplayer hobbies
>>
>>61660640
Sure, no problem, as long as you manage concurrent access
>>
Which is best for gaymes? SDL? OpenGL? SVGAlib? some toolkit? Anything else? A combination of some of them?

What are libraries providing portable (at least GNU+Linux and Winbloze, other platforms welcome) interface to use system calls (files operations, processes, threads, IPC, sockets n shit)?
>>
>>61660655
What are you doing here, go back to work.
>>
>>61660655
what's your favourite extension
>>
>>61660692
OpenGL + Qt for
>files operations, processes, threads, IPC, sockets, setting up the OpenGL window
>>
>>61660692
C or C++?
"Indie" game or some fully fledged 3D engine?
>>
File: clang.png (12KB, 628x128px) Image search: [Google]
clang.png
12KB, 628x128px
>>61660604
>This doesn't warn about checking for floating-point equality.
Does on my compiler.
>>
>>61660692
>waah waah /agdg/ was mean to me and told me to use an engine because I don't have any clue so I'm fleeing to another thread
Lmao you're not gonna make it anyways.
>>
>>61660728
"unsafe"
That newspeak this desu senpai
>>
How do I average 2 long ints in C?
>>
>>61660692
>asking about window frameworks/graphics API
Assuming you're making an engine.
OpenGL+glfw is very nice. SDL is also fine but i prefer GLFW.
SFML is heavy handed and is absolutely a mess. Defining their own vec type and stuff instead of operating on yours is just a terrible idea.
>>
>>61660772
Should state "may be inaccurate" instead
>>
>>61660781
Halve them both and then adjust for the fractional parts.
>>
>>61660781
That would require you to be able to average regular ints, which cannot be done in C.
>>
>>61660716
Doesn't matter. Though I know C better so maybe I'll pick C++ to train C++ some more. Or both.
I'm just bored/wanna learn. I'll make something simple like a platformer or a space shooter. I doubt if I come with anything worth releasing, even for "Indie", provided I'd make it anyways.

>>61660732
:^)
>>
>>61660825
>I'm just bored/wanna learn. I'll make something simple like a platformer or a space shooter. I doubt if I come with anything worth releasing, even for "Indie", provided I'd make it anyways.
Just go with SDL or SFML, no reason to reinvent the wheel for such minimal project. If you go the C++ route the C++17 (assuming you have access to GCC 7.x and are willing to use experimental features) has got you covered for most things except maybe sockets but then you can go with Boost.Asio.
Although both SDL and SFML provide these utilities as well.
>>
>>61660781
What type do you want the result to be?
if it's double, you can do:
#include <math.h>
/* .. */
long a, b;
long avg_lt, avg_lr;
double avg_d;
/* ... */
avg_d = a + b / 2.;
avg_lt = (long) avg_d; /* this will truncate */
avg_lr = lround(avg_d);
>>
>>61660858
I'm stupid and forgot the parenthesis around a + b.
>>
>>61660665
But say if I initialise an object "x" and append it into list1 and list2.

And then I do something like list1["x"].changeID("benis")

The change is not reflected in the "x" object in list2?

As I understand it, as python is pass-by-value, both lists contain copies of "x" rather than a reference to the original "x"
>>
>>61660781
(a >> 1) + (b >> 1) + (a & b & 1)
>>
>>61660901
Can you explain how
(a & b & 1)
works?
>>
>>61660896
>list indexed using strings
>an object "x"
>pass-by-value
Dunno where to start. Go watch PyCon talks on Jewtube kiddo thx
>>
>>61660896
Try it yourself.
lista = []
listb = lista
lista.append("foo")
print listb

Don't confuse reference types with pass by reference.
>>
>>61660925
It works.
>>
>>61660925
If either or both of the numbers are odd, that expression returns 1. Otherwise the expression returns 0.
>>
>>61660941
Seeing that it ends with "& 1", and 1 in binary is 000...001 for however many bits there are in a long int, then this either returns 1 or 0.
>>
still going through problems to learn java better

also trying to start learning clojure cause there's a project i'd really like to contribute to.
>>
>>61660959
Exactly.
>>
>>61660856
>no reason to reinvent the wheel for such minimal project
On the other hand, reinventing the wheel for such minimal project is much easier than reinventing the wheel and doing a big one.
I thought I would use SDL cause some time ago I saw some examples with SDL and emscripten. That would be fun to do as well. Haven't heard of SFML, thanks.

If I end up reimplementing the same shit to try out all of the technologies, I'm fine with it, as long as I do just a trivial game.
>>
>>61660927
Lad it was a quick example via phone posting at 5am.
>>
>>61660950
>if either
shouldn't it be (a | b) & 1?
>>
>>61660901
(a >> 1) + //divide by 2
(b >> 1) + //divide by 2
(a & b & 1) //add in the first bit if it was present in either of the values (since 0.5 would be rounded up)

Correct?
>>
>>61660950
Nope.
>>
If I learn to disassemble, debug and reverse engineer my C programs, will I become a better programmer?
>>
>>61660983
I realized that just after I posted.
>>
>>61660986
You should disassemble your C programs just to make sure your compiler isn't spitting out shit code.
>>
are logical operators associative?
>>
>>61660984
Na mate. With & it has to be both, so this rounds downwards. The mean of 0 and 1 is computed as 0
>>
>>61661027
Obviously yes.
>>
>>61660667
my friend works for a startup, they just brew beer, play ff14, order lunch on company dollar and work from 10 to 8
>>
File: image.png (33KB, 820x729px) Image search: [Google]
image.png
33KB, 820x729px
help me goys
>>
Given a time, 24-hour format, HH:MM, write code that would output the time as spoken in English.

Example input:
00:00
01:30
12:05
14:01
20:29
21:00


Example output:
It's twelve am
It's one thirty am
It's twelve oh five pm
It's two oh one pm
It's eight twenty nine pm
It's nine pm


Reddit was able to solve this. Are you?
>>
File: Screenshot_20170801-053337.png (64KB, 1080x1920px) Image search: [Google]
Screenshot_20170801-053337.png
64KB, 1080x1920px
>>61660936
Hey thanks anon, was trying to work out how I came to that incorrect assumption.

I think when I tested this same concept, because I my queue was a multiprocess object when I appended my object to both the queue and a global list I was using to track the state, some weirdness happens with the address space of the multiprocess.queue. which makes sense I guess.

Anyway, lots of fun stuff to test :)
>>
>>61661434
Sure but I'm not doing your homework for you.
>>
>>61661148
you mean 8 to 10 right?
>>
I know C, I learned it using the K&R book. I liked that book.
Now I want to learn another programming language, namely Java (not because I really want to, but because I have to for school). Is there a book that is to Java what K&R is to C?
>>
Reminder that C++ has had modules since before it was C++.

A header isn't a module, it's just a public interface for one. Modules themselves are called "compilation units." Despite being very low level, they support all the features you'd expect from any implementation of the concept of modules.
>>
>>61661503
>learning java from book when you already know programming language
Read the compiler manual so you can compile your source.
Skim trough the standard libraries and inbuild operators from the compilers documentation and refer to them when needed.
>>
>>61661527
>>61656662
>>
>>61661527
Is there a tool that will automatically generate these interfaces to compilation units?
>>
>>61661487
no, they work a lot
>>
File: 1496061516822.jpg (113KB, 573x892px) Image search: [Google]
1496061516822.jpg
113KB, 573x892px
>>61661625
Bump. I'm interested in that since I don't understand why nobody is doing it.
>>
>>61661625
Probably.
It surely wouldn't be too hard, because a compilation unit is just an ELF file, and there's already a very similar tool, whose name I can't remember, that parses ELF files and extracts and lists all the public symbols and their types.
>>
>>61661625
Requires system that uses ELF format, which is basically all of the Unix-like operating systems. Not sure if it works with sepples though.
>Assuming your binary was built with debug info, you can get function type, argument types, etc. etc. by reading DWARF debug format, which readelf -wi will dump.
https://stackoverflow.com/questions/15573275/how-to-extract-function-prototype-from-an-elf-file
>>
>>61661853
>Not sure if it works with sepples though.
Oh, right, the name mangling.
>>
>>61661883
>pick sepples-aware tool
>problem solved

Aren't there tools that could parse the sources instead though?
>>
File: anal beads.png (26KB, 773x437px) Image search: [Google]
anal beads.png
26KB, 773x437px
>>61661434
dude ternaries lmao

slight formatting differences, call the cops, I don't give a fuck
>>
>>61661951
>static void Main(string[] args)
>static
>Main
How the hell is it supposed to find the damn thing then?
>>
File: 1474673432811.png (3KB, 496x342px) Image search: [Google]
1474673432811.png
3KB, 496x342px
>>61661434
I did the hours part, and verified that it works correctly.
The minutes are left as an exercice for the reader.
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *hour(short int t);

/*
* int main(int argc, char *argv[])
*/
int main(void)
{
short int i;

for (i = 0; i < 24; ++i) {
char *s = hour(i);
printf("%02hd:%02hd => %s\n", i, 0, s);
free(s);
}

exit(EXIT_SUCCESS);
}

char *hour(short int t)
{
const char *hours[] = {
"twelve", "one", "two", "three", "four", "five",
"six", "seven", "eight", "nine", "ten", "eleven"
};
const bool _am = t < 12;
const char *am = _am ? " am" : " pm";
char *str;
const char *hour_ptr;
size_t len;

hour_ptr = hours[t - (_am ? 0 : 12)];
len = strlen(hour_ptr) + strlen(am) + 1;

if (!(str = calloc(len, 1))) {
fputs("Failed to allocate memory\n", stderr);
return NULL;
}
strncpy(str, hour_ptr, strlen(hour_ptr) + 1);
strncat(str, am, strlen(am) + 1);

return str;
}
>>
>>61662024
not sure if trolling
>>
>>61662024
What are you talking about? The entry point is required to be named Main(), must be static, and can return int or void.
>>
>>61661951
static string HumanizeTime(string input)
{
var parts = input.Split(':');
var hourpart = parts.First().ToInt32();
var minutepart = parts.Last().ToInt32();
var time = (
hour: hourpart == 0 ? "twelve" :
hourpart > 12 ? (hourpart - 12).ToWords() :
hourpart.ToWords(),
minute: minutepart == 0 ? "" :
minutepart < 10 ? "oh " + minutepart.ToWords() + " " :
minutepart.ToWords() + " ",
ampm: hourpart > 12 ? "PM" : "AM");

return $"It's {time.hour} {time.minute}{time.ampm}";
}
>>
>>61662067
>can return int or void.
What language is this?
C and C++ require main to return an int.
http://www.stroustrup.com/bs_faq2.html#void-main
>>
>>61662041
>>61662067
But if the symbol Main is static then how does the runtime find it?
>>
>>61662092
C#
>>
>>61662092
>>61662114
It's C#. Static here is being used in the OOP sense, not the C linkage sense.
>>
>>61662092
C# retard

Lurk more
>>
>>61662123
>Static here is being used in the OOP sense, not the C linkage sense.
I have not heard of this "OOP sense"??????
Will have to bone up on this later
>>
>>61662130
Not knowing C# does not make me a retard. And lurking more is not gonna make me a C# expert.
>>
>>61662139
object independent
>>
>>61662139
LURK
URKL
RKLU
KLUR

MORE
OREM
REMO
EMOR
>>
>>61662139
Static on a method basically means you don't have to have an instance of the object to act upon.

https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/static
>>
>>61662170
>REMO
>EMOR
uint32_t REMO = *(uint32_t *)"REMO";
uint32_t EMOR = *(uint32_t *)"EMOR";
uint64_t ZOOSMELL = *(uint64_t *)"ZOOSMELL";
uint64_t POOPLORD = *(uint64_t *)"POOPLORD";
>>
>>61662170
Make a program that, given a sentence, such as "Hello world", produces the output:
HELLO
ELLOH
LLOHE
LOHEL
OHELL

WORLD
ORLDW
RLDWO
LDWOR
DWORL
It would be good for shitposting.
>>
>>61662167
>>61662176
Oh. makes sense thanks
>>61662170
nice meme
>>
>>61662158
stfu then. going "omg lol lol lol howsit gonna find it if it's internally linked" without even thinking for one second that it be that "static" must have a different meaning in this language you don't know makes you sound self-unaware. Gee
>>
>>61662234
It wasn't me who said that.
>>
>>61662251
Oh I'm so sorry, I should have guessed. Are you ok?

CRYBABY
RYBABYC
YBABYCR
BABYCRY
ABYCRYB
BYCRYBA
YCRYBAB
>>
What's your preferred concurrency model?
>>
>>61662310
Event loop with fibers

Absolutely delicious
>>
>>61660501
>>61660523
>>61660639
Thank you.
>>
import Foundation

var output: CInt = 0
getInput(&output)
println(output)

Who thought that not having statement terminator was good idea?
>>
>>61662310
autogenerated monadic state machines autogenerated from language keywords
>>
>>61662407
Whoever made JavaScript, Python, and Go.
>>
>>61662444
Javascript? Sure anon?
>>
>>61662407
What language is this?
>>
>>61662481
Semicolons are optional
>>
>>61659064
You a free to quit any "dead end job", work together a portfolio and find something better.
>>
>>61656662
>importclude
kek
>>
>>61662481
>He hasn't heard of semicolon insertion
What does this function return?
function foo() {
return
{
prop : "val"
};
}
>>
>>61662482
swift

>>61662444
Brendan Eich, Rossum and Pike are all faggots.
>>
>>61662130
>>61662170
>>61662234
>>61662307
why yall fag tho
>>
>>61662407
Open a math textbook and show me the statement terminators anon. Lines are extremely intuitive for humans, and algorithms virtually don't see the difference.
>>
>>61662544
Autism.
>>
>>61662586
Jos p(x) on predikaatti x = 2 , ja q(x) predikaatti x + 2 = 4 , niin implikaatio 'jos x = 2 ,
niin x + 2 = 4 ' (eli p(x) ⇒ q(x) ) on tunnetusti tosi.

>.
>>
>>61662586
>Open a math textbook and show me the statement terminators anon.
Math doesn't have statements.
>>
>>61662618
wtf is this pig language
>>
>>61662649
mongolian
>>
>>61662649
>not english
>ergo pig language
wow what a faggot
>>
>>61662619
Let X be the set of dumb statements by this anon. Then X is non-empty.
>>
>>61662671
yeah that was pretty much my thought process
there are some non english languages that arent pig languages like wapanese for example
>>
File: 1493306834231.jpg (66KB, 419x249px) Image search: [Google]
1493306834231.jpg
66KB, 419x249px
>>61662664
>>61662649
>>61662671
>>
File: file.png (139KB, 719x470px) Image search: [Google]
file.png
139KB, 719x470px
>>61662586
here you go anon
>>
>>61662686
That's not a statement in the programming sense of the term. That's just a boolean expression.
That's all math has. Declarations and expressions. There are no statements. There is no need for any statements because there are no side effects.
>>
File: 360h.jpg (19KB, 274x360px) Image search: [Google]
360h.jpg
19KB, 274x360px
Web monkey here. Looking to play with the big boys' toys. Is there anything out there that makes a better babby's first C book than K&R? I was looking at pic related but it assumes a fair bit of experience.
>>
>>61662586
You ever heard of a period anon? A semicolon is just an almost period; it's not that hard you baka.
>>
>>61662764
>You ever heard of a period anon?
...
(hue hue)
>>
>>61662719
>There is no need for any statements because there are no side effects.
They never taught you any algorithms in math class? Not newton's method? Not Heron's method? Not even greatest divisor?

Most math professors don't stress about writing recursive side effect free versions.
>>
File: 1476230511376.png (81KB, 556x430px) Image search: [Google]
1476230511376.png
81KB, 556x430px
>>61662699
>>
>>61662838
>Most math professors don't stress about writing recursive side effect free versions.
They wouldn't need to, those are all already side effect free, if not recursive.
No mutation even takes place, just re-declaration.
>>
>>61662764
>You ever heard of a period anon?
Said the actress to the bishop.
>>
>>61662760
>C
>big boy anything

rofl, C is literally like 23 things that you just combine in different ways
>>
new thread
>>61662888
>>
>>61662586
I like to handle whitespace as I please.
This faggotry has left languages like go unable to even do trivial things like putting the opening braces on the next line, because the compiler is going to be inserting semicolons wherever it finds a newline character.
I can put my own semicolons, thank you very much.
>>
>>61662719
Technically, it's called a proposition. Or so I've been taught.
>>
>>61662027
>malloc for less than 10 bytes
>>
>>61662760
Check out “C Programming: A Modern Approach” by K. N. King, and “C in a Nutshell” by Peter Prinz and Tony Crawford.

>>61662935
We don't want to waste memory now, do we?
>>
>>61663039
why malloc what you can stack-allocate?
>>
>>61662760
>I was looking at pic related but it assumes a fair bit of experience.
This book has the huge flaw that it introduces automake as a 21st century tool.
These >>61663039 are ok.
Thread posts: 322
Thread images: 34


[Boards: 3 / a / aco / adv / an / asp / b / bant / biz / c / can / cgl / ck / cm / co / cock / d / diy / e / fa / fap / fit / fitlit / g / gd / gif / h / hc / his / hm / hr / i / ic / int / jp / k / lgbt / lit / m / mlp / mlpol / mo / mtv / mu / n / news / o / out / outsoc / p / po / pol / qa / qst / r / r9k / s / s4s / sci / soc / sp / spa / t / tg / toy / trash / trv / tv / u / v / vg / vint / vip / vp / vr / w / wg / wsg / wsr / x / y] [Search | Top | Home]

I'm aware that Imgur.com will stop allowing adult images since 15th of May. I'm taking actions to backup as much data as possible.
Read more on this topic here - https://archived.moe/talk/thread/1694/


If you need a post removed click on it's [Report] button and follow the instruction.
DMCA Content Takedown via dmca.com
All images are hosted on imgur.com.
If you like this website please support us by donating with Bitcoins at 16mKtbZiwW52BLkibtCr8jUg2KVUMTxVQ5
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.
This is a 4chan archive - all of the content originated from that site.
This means that RandomArchive shows their content, archived.
If you need information for a Poster - contact them.