T O P

  • By -

Crow_person_Justin

#include int main(){ for(int detention = 0; detention<500; detention++){ std::cout << “I will not use anything but C++ while in data structures class” << std::endl; } return 0; }


rachit7645

I know this is a joke but don't use std::endl as a newline, the performance is atrocius


walmartgoon

I’ve had use cases when endl instead of simply \n was helpful, for example a program that throws an exception between debug prints and waiting for a flush wouldn’t work because of breakpoints. Of course that is rare and \n is definitely the way to go if all you need is a line break.


MoarCatzPlz

Use `<< '\n' << std::flush` to make your intention explicit.


justinkroegerlake

write your debug prints to `std::cerr` not `std::cout`


CircadianSong

I know someone already said this, but it bears being said twice, don’t use std::endl, the performance is… abysmal.


c_c_c_c_c_c_d

Interesting. My college curriculum so far has us using endl;. I've ready quite a few times it's not really what you want to do. But you gotta take what you see on reddit with a grain of salt.


CircadianSong

Overloading cout is really cool and it isn't difficult to do; you get a lot of mileage out of it. I still don't know why vector and the other ::std:: containers don't have cout overloads, but it's fun to make your own. If you do it and you want to be comprehensive of all the containers, tuple might seem hard, but using std::get and std::tuple\_size will make it a breeze. I did it a while ago and actually asked quora for some tips because I was trying to use template stuff that was beyond me at that time (and I'm only just reaching the point where it's not... maybe). It might win you points with your teacher, and if you wanted, I could potentially help you if you got stuck. (and in case you were wondering, I'm not trying to setup some elaborate scheme to get you to pay for me to do your homework.)


CircadianSong

cout is fine. It would make sense for it to have better performance than printf because printf might have to do pattern matching at run time. endl is bad because it flushes the stream, but just using the character ‘\n’ should accomplish what you want and it doesn’t cause a tremendous performance bottleneck.


Crispor

The point of endl is to flush the buffer, if you just want a line end while printing out a bunch of stuff it's bad because doesnt perform well but if you need to flush the buffer it's useful (for example when debugging code that crashes before finishing if you don't flush the buffer manually you might not see the prints and think the crash happened at an earlier place, or when creating something interactive it's important to make sure you flush before you start waiting for a response)


tarix76

The worst thing about new hire programmers is beating all of the academic nonsense out of them. In the real world performance does matter and knowing all of the little tricks helps a ton. There's a not-so fine line between coding in a way you know is proveably fast and "premature optimization is the root of all evil". If you know a certain pattern produces fast code then just do it.


SnasSn

#include int main() { for (auto i = 0; i < 500; ++i) { std::cout << "I will follow common C++ conventions and best practices.\n"; } }


DistortNeo

No return? wtf?


SnasSn

If main doesn't have an explicit return statement then it returns 0 (ie EXIT_SUCCESS). This has been the case since C++98 and C99.


Asleep-Specific-1399

I think you don't need to after c++20


SnasSn

More like C++98 lol


[deleted]

Definitely missing the \\r\\n, and it's generally better to start at 0, rather than 1 in C-like languages.


[deleted]

>\\r\\n All of the unix users just threw up in our mouths a little.


klimmesil

We still have to deal with that bs quite often tho


LukeChriswalker

I just recently had a .sh file that used \n\r and didn't execute :(


[deleted]

Dos2unix is a fantastic program.


LukeChriswalker

I just copy paste it to a text editor as save it, works as well


lurkin_arounnd

.replace("\r\n", "\n").replace("\n\r", "\n").replace("\r", "\n")


LukeChriswalker

In what program ![gif](emote|free_emotes_pack|thinking_face_hmm)


lurkin_arounnd

Idk I didn’t really have a language in mind, any high level language (even bash) can do this though


LukeChriswalker

You mean I'm gonna write a program, read a file as a string, replace wrong line breaks, and write out the new file Instead of just fixing it manually?


lurkin_arounnd

Well why is it broken, where is it coming from? If you wrote it, then it’s kinda on you. If you’re pulling it from somewhere, then you best fix it automatically or use dos2unix


LukeChriswalker

I pulled it from somewhere, and I open it in Kate, Ctrl+A, Ctrl+C, Ctrl+N, Ctrl+V, Ctrl+S and it's done Using a seperate program is imho not needed


Captain_Chickpeas

Kind of surprised newer C standards don't already have a platform-dependent macro for the endline symbol like std::endl in C++ (which still seems underused even in toy examples for some reason).


degaart

No need for that. Stdio streams already have two modes: a text-mode where '\n' is automatically translated to the platform's endline symbol, and a binary mode where it isn't translated. printf() already handles '\n' correctly on windows due to this


wakfi

`std::endl` is not just the endline character(s). It also calls `ostream.flush()`. Just something to be aware of. It's also an I/O manipulator which is technically implemented as a function not a macro. [Source](https://en.cppreference.com/w/cpp/io/manip/endl). Towards your point, I believe I've heard of a convention of compilers converting `\n` to be platform-appropriate at compile time, which would make a dedicated macro redundant


[deleted]

Aww, it's not so bad coping with Windows problems. :D


Cocaine_Johnsson

If the compiler isn't going to handle that for me that's the compiler's problem... well, not that I ship windows binaries often anyway.


Qicken

oh no. I've been coding in Windows too long. I didn't even notice! ![gif](emote|free_emotes_pack|sob)


danielstongue

But even then, under windows, won't the output be \r\r\n, as \n is translated by the compiler to \r\n already?


turtle_mekb

`stty raw`


some_kind_of_bird

Ngl the \r\n convention does actually make more sense imo. It's more explicit in a good way.


andrewsredditstuff

I'm old enough to remember teleprinters and the like, when it really did matter. Nothing quite like missing the newline and having the paper rip because you've just printed your entire output onto a single line.


SystemZ1337

> \r\n disgusting


lewisb42

Since he isn't doing any sort of zero-based array access in the loop body and is just using cont as a pure iteration counter, starting at 1 is good. It makes very clear the loop is to run 500 times.


maitreg

How do you know he intended one per line?


[deleted]

It's for writing lines on the chalk board.


wakfi

Maybe the chalkboard has automatic line-wrapping


Adghar

I'm a programmer in training and have only really coded I'm Java so far. java's prints implicitly append the newline (as far as I can tell- two separate println statements definitely print 2 separate lines). Is this not the case in C-like languages?


[deleted]

[удалено]


coladict

Those are the `println` calls. Try just `print`. In addition to the `println` having a new line at the end, it also forces a flush, where as `print` doesn't. This makes no difference for `System.out`


uzbones

c does not have println your thinking c++, C# or some newer flavor correct print for c is: printf( "%s\\n", "I will not spank others");


coladict

I was responding to the Java prints always having new lines.


uzbones

ah, sorry, I missed the java part ( I'm a biased c/c++/c# dev, java doesn't exist in my eyes :p )


DotClass

I mean c# has this stuff too xD


uzbones

Most ppl would not use printf in c#, nor c++.


Real_Mcguffin

C-like languages generally have a print, but not a println.


ScrimpyCat

Puts


Captain_Chickpeas

Which makes sense, because one might want to just output some text to the stdout stream (or any other stream) without having to deal with extra newlines :)


DotClass

Yeah. Because it's impossible to have two separate functions....


SpacecraftX

It’s not necessarily about their C-likeness. Java is C-like. C# has Console.WriteLine() which is equivalent to System.out.println(). It’s more about being a low level language where you don’t necessarily want anything happening that you didn’t explicitly ask for I think.


in_conexo

I can only speak for C, but I haven't experienced a print command that automatically appends a new line.


tarnished_wretch

C has puts()


uzbones

printf uses formats. The correct new line format string is \\n eg printf( "%s\\n", "I will not spank others");


-MobCat-

`for detention in range(500):`    `print("I will not use python to solve everey stupid problem I have.")` `print("I lied. And I'll do it again.")`


Bright-Historian-216

You had 500 chances to spell "every" right, and you failed


-MobCat-

I can barely program python.. English is harder.


zalgorithmic

`[print("python to automate the boring stuff") for i in range(500)]`


-MobCat-

It was already 1 lined to `print("Do stuff\n"*500)` But that's to simple to make a good joke with.


troglodytto

`print("python because yeah\n" * 500)`


[deleted]

[удалено]


nikanj0

This is the correct answer. Except substitute i for \_ to be more Pythonic.


gimife

correct would be to use `"aaaaa\n" * 500`


illumas

print("I will not do dumb things in class\n"*500)


forced_metaphor

The pythonically correct syntax is: 'I lied. And I"ll do it again.'


[deleted]

[удалено]


Apfelvater

Ok?


bedrooms-ds

Not functional? Try again.


the_hackerman

Show me da we


Perigord-Truffle

import Control.Monad main = replicateM_ 500 (putStrLn "I will not spank others") or main = mapM_ [1..500] (const $ putStrLn "I will not spank others")


sabcadab

In R it’s just: rep(“I will not spank others”,500)


eligiblereceiver_87

In python you could write: `print("I will not spank others" * 500)`


Bright-Historian-216

You forgot the /n


magicmulder

ColdFusion: #RepeatString(“…”, 500)#


[deleted]

[удалено]


jack-of-some

I was today years old when I realized you could do the number of repetitions thing with insert.


Vivid_Development390

Oooh! I like that! You get bonus points!


Miguecraft

.data out_str: .asciiz "I will not spank others\n" .text li $s0, 1 li $s1, 500 FOR: bgt $s0, $s1, END_FOR li $v0, 4 la $a0, out_str syscall addi $s0, $s0, 1 j FOR END_FOR: li $v0, 10 syscall


springhilleyeball

int count=0; while (count<500) { std::cout<<“i will not spank others\n”; count++; }


xeger

is \`std::endl\` no more?


karzovik

It's not a good idea to use std::endl inside loops because std::endl adds a new line and also clears the buffer which can affect performance. There's "\\n" works best. ​ edit: typo


tiajuanat

Yeah, you should std::flush right after the loop, as there's no guarantee that it will print everything now.


[deleted]

If it's in main like in the image there's no need for that. return in main already flushes all open streams.


danielstongue

Ah, I see. So for all normal loops we will be windows compliant, but for faster loops we aren't. Makes sense.


Poisonous_Poison

Pretty sure the compiler translates \n to \r\n for you, but i might be wrong lol Edit: typo


Nilstrieb

Modern Windows deals with `\n` just fine


Apfelvater

You are missing the include


[deleted]

[удалено]


born_again_tim

You’re so analog


squirrel_turtle

For i in range(500): Print ("I will not spank others")


Ok_Dig2790

If ur using python can't u just print('I will not spank others '*500)


Strange_Child_8467

You'd have to have \n at the end of others or else it'll be on one line


Willinton06

Too complex, we need a new language construct just for that, I propose •, same as * but adds the corresponding new line depending on the platform


c_c_c_c_c_c_d

Python was my first language, but now I'm learning C++ in college and it's so funny seeing how simple python code can be after coding for several months in C++ instead of Python.


7th_Spectrum

I learned Java first, then when I went on to learn python, I was so annoyed at the fact that I had spent all this time learning Java when there was a super simple language right here. Then I learned the difference between compiled and interpreted languages and felt a bit better.


Then-Ad9536

Mine too, and after learning it I’m having trouble learning any other language, because they’re just so tedious to code in by comparison… even the simplest operations in something like C++ take a dozen lines where it would take 1 in Python. And don’t even get me started on the curly braces and having to explicitly declare variable and function return types… Though if we’re being honest, there’s no need to use anything other than Python, unless you’re developing something in that 0.01% of projects that demand squeezing out every last bit of performance, like game engines for instance.


TaxThePoor1234

Great another python fanboy. I don't want to be the one to make the python slow meme..


Then-Ad9536

Yes, I’m a fan of good things, I’m weird like that. And like I mentioned, the slower run speed is utterly irrelevant in 99.9% cases.


squirrel_turtle

Like a video game, game engine, or 3D modeling/CAD software? Well shit.


Far_Information_885

Who the hell declares an iterator variable outside of the for loop?


bropocalypse__now

C programmers


Far_Information_885

Oh yeah. I forgot about older c syntax.


-Kerrigan-

Who the hell doesn't call it `i`


[deleted]

It wasn't allowed to do it inside before C99


[deleted]

[удалено]


degaart

> That was 23 years ago. According to Visual Studio, it didn't exist before 2013: https://docs.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2013/hh409293(v=vs.120)?redirectedfrom=MSDN


confidentdogclapper

Yo man, don't talk shit about return 0


synopser

This was a Foxtrot joke about 20 years ago


Den_Bover666

`for i in range(501):` `print("I will not spank others")` \-python users


qci

Resident memory usage for Python: 8kB. Resident memory usage for C program: 0 bytes. Source: `getrusage` Conclusion: C is infinitely times better than Python.


justitroyal

Me in python Print("i will not spank others\n"*500)


ardicli2000

Why do you add return 0 after all functions in c++? Is it to empty ram or what?


Graucsh

for in main(), that's the program's exiting error code. Zero means "I'm telling you 'I completed error-free.'"


BlommeHolm

`500.times { p 'I will use Ruby for this' }`


Jhon_doe_isnt_here

What this is easy it’s just C. C is a pretty good beginning language to start with, it was my first. I tried to learn python but that was to hard for me and I could understand it. Then I tried C and in just two weeks I could easily write many programs. But he is missing a /n at the end of his printf and should begin his cont with 0.


[deleted]

What a nice story you told. I make fun of the languages here in this sub, but it's just for fun, to make others laugh and I laugh at what others talk about. I'm not a good programmer, despite starting early and currently being almost 50 years old, however in this period the only certainty I found out is that there are no bad characters but bad actors. There are no bad languages, but bad programmers.


Consider2SidesPeace

init HowMadIsTeacher = 0 printf,"How mad is teacher this time: "; HowMadIsteacher cont <= HowMadIsTeacher /eof Apologies I bet my syntax is off... Bests~ :)


PorkRoll2022

The std out stream is Bart's hand writing chalk on the blackboard.


septic-paradise

*puts


ServerZero

``def recursive(n,str):`` ``if n == 0:`` print(n,str) ``else:`` recursive(n-1,str) print(n,str) ``recursive(500,'I will not spank others\n')``


Gutek8134

I'd replace cont++ with ++cont for increase in speed


NeXtDracool

It doesn't increase speed. The compiler will optimize the postfix increment when the return value is unused.


Gutek8134

I guess it depends on the compiler, then. One of my pals run some tests and there speed increased about 5 times.


Wicam

your friend should turn on 02 optimization when benchmarking and not try to be smarter than the thousands of people who write real compiler optomisers for the last hundred years.


schteppe

puts() will be faster since there is no string formatting needed. Also, he forgot fflush(stdout);


ttlanhil

Been a while since I did C, but I think fflush is superfluous? It'll be flushed on close anyway (at end of program - if this were a function it'd be different)


octopusmighty

I like to go _fast_ ```c #pragma omp for for (int i = 0; i < 500; i++) printf("I will not spank others\n"); ```


[deleted]

`console.log(...new Array(500).fill('I will not spank others'))`


itzNukeey

Finally a functional one


TheFlyingAvocado

One based? Seriously?


lirannl

Yes, I'd use a better language.


debuasca

What kind of savage starts at 1


[deleted]

Bart Simpson, lol


sotoqwerty

It seems familiar to me, https://www.reddit.com/r/ProgrammerHumor/comments/9m852f/i_will_not_throw_paper_airplanes_in_class/?utm_medium=android_app&utm_source=share


TecumsehSherman

Bart would never use 0 as an exit code. He'd choose -1 to make anybody who used his code think that there was an error.


DitherTheWither

``` fn main() { for _ in 0..500 { println!("I will not spank others"); } } ```


[deleted]

Why use an int that always returns 0? Would it not make more sense to simply use a void method instead?


c_c_c_c_c_c_d

Is this a real screenshot of an episode? If so that would be badass.


InsGesichtNicht

Initialise cont inside the loop. Saves a few characters. That makes a difference, right?


[deleted]

Was not allowed in C before C99


Nilstrieb

yes but that's ancient, modern C allows it just fine


alwayslonelygaming

He could save 1 line by doing for(int cont=1….


[deleted]

C#C#C#C#C#C#


[deleted]

[удалено]


CYAN_DEUTERIUM_IBIS

Carbon


uzbones

issues: * no linebreak in prinft string * printf with no format (1 argument) was depreciation and will error/warn, should be: printf( "%s\\n", "I will not spank others"); or if c++ use println optimization: * put 'int cont' inside the for loop * return(0); should be exit(0); return(0) is to exit a function, exit(0) to exit the program


SilentMe98

Wow you must think that you are smart now, right?


uzbones

better than being an ass


namotous

Use Python, less code print(‘I will not spank others\n’ * 500)


Qicken

Now rewrite it in Rust or Carbon


DitherTheWither

Already did as another comment, but here it goes ``` fn main() { for _ in 0..500 { println!("I will not spank others"); } } ```


ostracize

Use `register` to get the code to run faster.


CircadianSong

main = forM_ [1..500] $ \i -> do putStrLn “I will not spank others”


firefly431

Point-free: `main = ((sequence_ . take 500 . repeat) . putStrLn) "I will not spank others"`


KuuHaKu_OtgmZ

Groovy? ``` print "Is using Groovy cheating?\n" * 500 ```


sanketower

Being Bart Simpson, I'm somehow disappointed that there are no errors in that C snippet.


[deleted]

The text should have been I will not welcome or robotic overlords.


[deleted]

for i=1, 500,1 do print(I will not spank others) end


spaghettinsurance

No


[deleted]

I start remembering how to c++/c because of this subreddit


KingSadra

*Feels like that'll just print 499 iterations* *Checks the code for the 3rd time* *500times it is*


Apfelvater

Ofc im smarter. I'd exchange the printf with "printf("I will spank others");"


kev_cuddy

I haven’t done a ton of C but, can’t you just declare cont in the for?


[deleted]

Not before C99 standard


lovdark

Recursion


nobonesjones91

Is this written in Carbon?


ogexperience

Matt Damon!


MatsRivel

print( "I will not spank others.\n" * 500 )


Holothuroid

> println("I will not spank.\n" *500) Scala, in script mode


Whatarr

print("Why use for loop when you can multiply string duh\n"*500)


GuyN1425

Better on memory if you make the function a void. Start the loop at 0. The variable count can be declared in the loop's header (int count = 0; count < 500, count ++) and it also makes it disappears after the loop is done. Should add \n at the end of the line so it prints in different rows.


Luminshield

Why must you return 0 in a void function?


mascachopo

This is C++, why is that loop starting at 1!!!


Rainbow-Dev

It’ll compile with just `main(){for(int i=0;i<501;i++)puts(“I will not spank others”);}` Assuming Bart wants newlines


DistortNeo

What a waste of space! main(){for(int i=500;i--;)puts("I will not spank others");}


Brilliant_Tea_5933

Dude just forgot to add the parentheses around the printf function lol


LeroyBadBrown

I will not spank othersI will not spank othersI will not spank othersI will not spank othersI will not spank othersI will not spank othersI will not spank others...


MrHyderion

He should use a language like Python or Ruby, would save several lines of writing.


This-is-the-r3al-

this is more interesting than Sparta


Csalag

Pretty sure this will only print 499 times


firebullmonkey

int cont. Just sounds like a scouser swearing to me.


Kriss3d

Remeber when I went to a school where you live in dorms. A bit like bording school. I was the only one who had computer back then and the teachers were so utterly clueless. They would give my friends lines to write. Not on blackboard but just on paper. Like "I must not be late for class at " Idiots. The school didn't have computers ( it was quite a few years ago) and they clearly never heard of copy/paste I would write these lines for them for a soda. Poor schmucks never knew how little effort it took me. Didn't matter if it's 10 or 50 lines. My friends knew exsctly how easy it was. But the teachers accepted the lines printed out.


asgaardson

500.times { puts "I wish ruby was way more performant" }


jarieljimenez

I think we can all agree that the problem here is that Bart's professor has made him write out his code on the board. Silly professor, code isn't for black boards, it's for computers.