[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]

Alright /g/. cout or printf? Which one is better?

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: 98
Thread images: 5

File: The C Programming Language.png (107KB, 792x1023px) Image search: [Google]
The C Programming Language.png
107KB, 792x1023px
Alright /g/.
cout or printf? Which one is better?
>>
cout ofc
>>
The methodology that allows C's printf library to work the way it does is fully accessible to the user so they may write their own printf library.
It's called stdarg.h.

Good luck figuring out how C++98 overloaded the goddamn >> << operators just to stream bits.
>>
>>60131631
format
>>
>>60131631
print! > printf > cout
>>
>>60131631
cout.
>>
The real question is "new" or "malloc"
>>
>>60131826
new ofc
>>
>>60131826
std::experimental::pmr::polymorphic_allocator or gtfo
>>
>>60131631
operator overloading was a mistake, but streams are nice
>>
>>60131826
make_shared :^)
>>
>>60131631
cout
>>
>>60131631
cout is like printf but for smart people.
>>
Professionals use printf.
>>
>>60131826
new is problematic because it's an operator. It has massive overhead if you wish to use another allocator.

With malloc you just change your calling convention. You can easily detect every instance of malloc and replace. If you aim to do the same with a codebase which uses new you'd either have to overload the new for every struct and class, including the primitives, or replace it all with different function calls.

It's beyond me why they would make it like this. They could easily have had a more convenient way to let you choose allocator without writing a massive set of overloads. As it stands the malloc interface is less of a bad design and more of a limited design.
>>
printf is way more readable
>>
>>60131899
>streams are nice
Elaborate.
>>
>>60133552
the pro with it being an operator is that you can overload it. Then you can use a memory pool, getting around the problem of allocating in runtime.
>>
>>60133758
I think streams are a good abstraction for I/O. The stream analogy works nicely for files, pipes, sockets, and terminal I/O. I think Java's Stream API is a bit more sensible, and I think the overloading of << and >> for stream reading and writing is very stupid.

Streams seem like overkill when writing simple text-only programs, but when managing multiple I/O sources, streams that can be opened and closed with uniform function names are nice.

In addition, while printf and family are not bad, the ability to overload the stream print and read methods for different data types is really convenient, and allows different libraries to present the same interface for printing, as well as for other forms of I/O.

I'm looking forward to when C++ has a cross-platform socket stream in the standard library, but I hear Boost has one already.
>>
>>60131631
Using printf:
unsigned a = 0x1337;
printf("0x%08X\n", a);


Using cout:
unsigned a = 0x1337;
std::cout << "0x" << std::hex << std::uppercase << a << std::nouppercase << std::dec << std::endl;


'nuff said
>>
>>60133948

void StreamPrintf(std::ostream stream, const char *format, ...) {
char buffer[1024];
va_list args;
memset(buffer, 0, sizeof buffer);
va_start(args, format);
vsnprintf(buffer, (sizeof buffer) - 1, format, args);
va_end(args);
stream << buffer;
}

void main(void) {
unsigned a = 0x1337;
StreamPrintf(std::cout, "0x%08X\n", a);
}
>>
>>60133882
So now you have to overload it for every single type anon. That's the problem.
New should be settable. (at least that's a simple solution, more is required)
>then you can use a memory pool
You could try any other allocation scheme, many of which require more than the operator new permits.
If you want a good solution you end up with a template/macro mess.

Of course you can get wherever you want with sufficient amounts of code but that's never what programming languages are about.
>>
>>60133989
I end up adding this function in every C++ program I write, the format system is really useful
>>
I love c++1x so I probably have brain damage but even I prefer printf
>>
>>60133997
>So now you have to overload it for every single type anon
no
>>
>>60131631
printf is good for quick and dirty output and simple things. It comes with the flexibility of C with all the security and other hazards of C.

cout has proper type checking and casting. Formatting is extremely explicit making code easier to read. Being able to pipe the stream wherever is also nice. Complex formatting jobs can be a bitch to write. Default buffering can do odd things on the command line. Sometimes overloaded or templated stream operators can shit themselves when converting code from ASCII to wide/unicode.
>>
>>60134008
me too, my man
>>
>>60134024
Explain how I can use a single allocator new for every type in the language without specifying it for my types.
>>
puts
>>
>>60131631
cout > printf but \n > endl by far
>>
>>60134053
>my types.
Oh and for the primitives too obviously.
>>
>>60134053
templates my dude, probably the most worthwhile C++ feature imo
>>
>>60134084
Would be nice if every language overloaded the '%' operator for strings like ruby and python.
>>
>>60134122
Isn't str.format() the preferred method in python now?
>>
>>60134119
I don't see how templates would automatically get you beyond what a global replacement would.
>>
>>60134284
Whoops, I was incorrect. I just checked what the operator overload options are for templates, and you're correct, templates would not resolve this. In that case then, why isn't a global replacement sufficient?
>>
>>60134340
Alignment mostly. You can always constrain yourself to the most extreme case for your machine but that's very wasteful.
If you look into actual shipping allocators they're not all that simple. I can't say I'd need more than adjusting alignment personally though.
>>
>>60131631
puts
>>
>>60134393
Hmm, well that's a pretty clear shortcoming in the language. I'd think that typespecific overloads for new would be a thing, but apparently not.
>>
>>60133997
>So now you have to overload it for every single type anon. That's the problem.

Naah, only for things that are allocated at runtime; which shouldn't be that much.
I don't even have to differentiate between an overloaded new and a regular new when doing the actual coding, just call new every time.

I think the power to define what the allocator actually does from time to time is better, plus it's type safe.
But I guess it's a matter of preference.
>>
>>60134472
ooh, another good thing I like about new, is that it actually calls the constructor of the object you want to allocate, whereas malloc does not.
>>
>>60131631
Both are garbage.
printf - runtime interpreting of the format string every time, slow as shit.
iostreams - just inherently slow as shit, global state changes, verbose as fuck.
>>
>>60134393
Maybe it'd be nice to be able to specify from a global set of allocators too.
>>60134405
Yeah you can overload for specific types but that's not really the end goal..
http://en.cppreference.com/w/cpp/memory/new/operator_new
As you see they're fixing alignment that with C++17.
They're super late.

Really it's kinda worthless to use half-assed features. I'd much rather just use a function-based interface at that point.
>>60134472
>only for things allocated at runtime
Anon this is all very trivial if you don't have any need for dynamic allocation obviously. Regardless of the amount that's being allocated you need good facilities to manage it well. Having to work around specific cases in your code is always a hassle, hits you in the morale pretty hard I'm sure you agree.
>>60134524
>printf - runtime interpreting of the format string every time, slow as shit.
Compilers often allow themselves to optimize many of the standard library features aggressively. But they certainly don't do it as well as you could with a custom solution. And of course their solutions aren't as good as they could be even for a generic case:
https://github.com/nothings/stb/blob/master/stb_sprintf.h
I kinda just assumed that these functions would be really well optimized but these numbers are nuts.
>>
>>60134631
Yes, there is a bit of hassle, but I firmly think it's worth it as I don't have to worry about allocating enough space. Heap corruptions are a nightmare to debug.
>>
>>60134188

print("{}".format("yes"))
>>
printf("std::cout");
>>
File: wrong.jpg (6KB, 225x225px) Image search: [Google]
wrong.jpg
6KB, 225x225px
>>60134713

print("{0}".format("yes"))
>>
>>60134903

im relative newfag so i dont know how to post code but the point is you need a 0 in the braces so that you could keep going with more insertion variables in the .format() call
>>
>>60134878
std::cout << "printf("std::cout << "printf("std::cout << ...
>>
>>60134918
it doesnt compile
>>
>>60131708
This.
>>
>>60134913
.format() will automatically go to the next positional argument after each {} in your string. You only need a number if you need a specific positional argument.
>>
File: puggly.jpg (17KB, 460x423px) Image search: [Google]
puggly.jpg
17KB, 460x423px
>>60135151

well i'll be... how did i never notice this?
>>
>>60131631
write(1, str, strlen(str)); ofc
>>
>>60134903
inferior
here's the supreme version

print(f"{'yes'}")
>>
File: franklymydear.jpg (22KB, 640x480px) Image search: [Google]
franklymydear.jpg
22KB, 640x480px
I quite admire the level of knowledge you guys got on this, but may I ask, is this book still relevant to learn C as its used today?

or should I go straight with C++?

Whatever your answer is, can you recommend a book?

thanks.
>>
>>60136863
if you don't know/know little C it's still relevant.
>>
>>60131708
This post is not meant for normal sjw tier /g users.
>>
I've been learning C off and on for a decade and over the past couple years it's become my go-to language and one I nearly know by heart

I can't think of any feature of C++ I miss, that couldn't be replaced by better design patterns anyways

objects and generics are bad for computers and bad for effectively solving problems
and even the things that are rationally modeled by objects can be designed just as easily by
struct object
and
 int object_method(struct object self)
>>
>>60137023
>objects and generics are bad for computers and bad for effectively solving problems
>and even the things that are rationally modeled by objects can be designed just as easily by
struct object

and
int object_method(struct object self)

Does KRC has this concept explained in it?
int object_method(struct object self)

I am in chapter 6 and haven't found this.
>>
>>60136863
Which book are you talking about nigger?
>>
>>60136863
>I quite admire the level of knowledge you guys got on this, but may I ask, is this book still relevant to learn C as its used today?
Barely. It only covers C89, and the terse programming style it promotes is too clever by half at best, outright dangerous at worst.

It is a neat historical artifact, and I have a copy for that reason alone, but I would never use it as a tutorial or a reference.
>>
>>60136863
Something Patrick Wyatt said in a Q&A where he was asked specifically about old books and if they're any good to read he mentioned K&R and how it didn't really help him much with programming in C coming from a Pascal background (indented audience for the book really).
Having learned from it I can't exactly say I'm as negative as he seemingly was but perhaps that's lack of greater insight. His complaint was that it teaches you about all the C features but it doesn't really give you ideas into how you would use them. Perhaps he had a period where he had issues supplementing that knowledge and it really stuck with him. But either way I see the case that it's not a particularly pragmatic book even though it may seem very down with the language. Learning materials that have you solve issues using what you learn would probably be more to his liking.
C++ books more often than not teaches the higher level parts of the language a lot. They have a tendency to shy away from teaching a good understanding of the basic blocks the language is based on.
I don't know of good C books but I'd look for that rather than reading K&R because I see the issues mentioned.
>>
>>60137100
It's just a function. It's not really a concept that needs explaining. Whereas in C++ all object methods are placed within the object itself, and called from the object, in C the object would hold just its data and it's 'methods' would be functions you'd call and just pass in the object as a parameter. For example, in C++ you'd do:
class Object {
int value;
void method() {
std::cout<<this->value<<std::endl;
}
};

in C you'd just do
struct object {
int value;
};
void object_method(struct object *this) {
printf("%d\n", this->value);
}


and going further with this idea you can easily make constructors, public and private data, etc. that you would find in C++ but actually isn't C++-exclusive.
>>
>>60137339
I have to ask why you don't prefer using the C++ version. It's equivalent and gives you plenty of convenience for that specific situation.
I don't find that object programming is ever that useful but if I were to do it I'd certainly pick C++ over C for it.
>>
>>60137412
You said it yourself, I don't find that object programming is ever that useful either.
Most of my projects are in C and I don't really use objects at all. But if I, for some reason, wanted to add sort of objects to something I worked on, I'd just do the latter in C and not switch the entire codebase to C++.

Also I hate the STL with a burning passion and that's reason enough for me to not want to use C++ ever.
>>
>>60131708
Friendly reminder that nested types of the form <<<T>>> are confused as shift operators AND stream operators because C++ is so shit.
>>
>>60136863
No, Gone With The Wind isn't particularly useful for learning C.
>>
>>60137439
Yes, Now I should ask you. The template is very powerful. I don't think C is capable of compile time(statically as some people say) decision of defining function signature or declaring function.Is it never required in software development or this can be achieved with some hacks in C?
>>
>>60137776
It can be achieved with hacks, to list some:
void pointers, opaque types, union types, tagged unions, macros.
But the idea is different. Usually in C you're very conscious of the kind of data you're using and only in very few cases will you want the same function for different types. Usually types are well-defined and the functions that operate them are just as well-defined. C is, in general, more concrete than abstract.
>>
System.out.println
>>
>>60137776
Most of my compile time evaluation is done by writing another program that outputs the data I wanted compile time evaluated.
It's not the most pretty but it beats constexpr, and it can be a rather slow solution usually as I just need to hash the source files to see if it needs to be compiled/re-run in my build system.

It's pretty nice for what it is but it's clearly not the strong suit of C. Data entry in C is very poor overall.
>>
>>60138310
You are saying abstract function definitions are not required as much as people think they would require?And if required C hacks are "better" or C hacks can get the job done while not being "better" than C++ couterpart?
>>
>>60131631
printf is faster than cout.

don't ask me how i know.
>>
>>60131631
putchar > all
>>
Can anyone explain this?
I used a constructor that has int type parameter.
So whatever int literal I pass it is copied to that parameter which I would use to initialize
int& i
member variable. But since contructor parameter was automatic/temporary object, how does that struct foo object still prints i member variable?
Is this some C++ "good guys" optimized thing or I am missing something?
#include<iostream>
struct foo{
int& i;
//foo(int& _i):i(_i){}
foo(int l):i(l){}
void print();
};
void foo::print(){
std::cout<<"Trying to print : "<<i<<"\n";
}
int main(){
int i1 = 2;
int i2 = 97;
struct foo ebin(i1);
ebin.print();
return 0;
}

>>
>>60131631
Both are inferior to echo
>>
File: 1473983755464.png (310KB, 655x977px) Image search: [Google]
1473983755464.png
310KB, 655x977px
Reminder that since c++14

return (x);

and
return x;


are two different things :^)
>>
>>60139010
How?
>>
>>60139031
I guess
 return (x) 

would cast it to the return type of declared return type of function. So basically more sjw elements. #FREEDOM
>>
>>60139031
I am not smart enough to explain so:
http://stackoverflow.com/a/25615981
>>
>>60138977
The real question is why are you doing "struct foo ebin()"?
>>
>>60139045
>>60139051
This is retarded
>>
>>60139051
C++ is such an intuitive language. And of course we all know about these fine relevant details in the language and then it's easy.
I don't see what people are complaining about when they say C++ is unwieldy.
>>
>>60139064
ebinnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn
>>
>>60139116
You don't need to specify that it's a struct when declaring it; foo ebin() would have been enough
>>
>>60131631
from __future__ import print_function
print(" is better")
>>
>>60137441
Not in C++11 anymore
>>
>>60139010
what the fuck? is this real?

im drunk
>>
>>60139156
i know that. u thought i would not know that?
I have OCD.
>>
puts
>>
>>60131631
only use getchar_unclocked() and putchar_unlocked()
All you need, and is up to 5x faster than printf/cout.
For example to read some integers with getchar_unlocked safely omiting whitespace:

template<typename T>
inline bool sc(T &num){
bool neg=0;
int c;
num=0;
while(c=getchar_unlocked(),c<33){if(c == EOF) return false;}
if(c=='-'){
neg=1;
c=getchar_unlocked();
}
for(;c>47;c=getchar_unlocked())
num=num*10+c-48;
if(neg)
num*=-1;
return true;
}
template<typename T, typename ...Args>
inline void sc(T &num, Args &...args){
bool neg=0;
int c;
num=0;
while(c=getchar_unlocked(),c<33){;}
if(c=='-'){
neg=1;
c=getchar_unlocked();
}
for(;c>47;c=getchar_unlocked())
num=num*10+c-48;
if(neg)
num*=-1;
sc(args...);
}


and then you can just get all numbers like this:
int a,b,c;
sc(a,b,c);


You can make this into 1 line, and put it into your c++ template file, really worth it man
>>
>>60131631
System.Console.Write
>>
>>60131631
puts
>>
>>60141866

mah nigga!
>>
>>60141866
Now, how are you gonna quickly output an integer, or input an integer?
>>
>>60131631
INT 21 AH=09
>>
>>60131631
The fact a language lets you do the same thing in more than one way = trash
Thread posts: 98
Thread images: 5


[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.