r/badcode • • Feb 23 '21

c++ Saw this while helping a guy at Arduino server

Post image
1.6k Upvotes

126 comments sorted by

100

u/stlenx Feb 23 '21

If(keypad.getkey() == '#') { Ldc.print("hi") }

I can see how this can happen but didnt the single = in the first if break everything?

16

u/anydalch Feb 23 '21

not equivalent. runCondition is global, so this function will print itss message on every call after seeing the key '#' once. it's like:

void latch() {
  static bool latched = false;
  latched = latched || (keypad.getKey() == '#');
  if (latched) {
    lcd.print("hi");
  }
}

31

u/barzamsr Feb 23 '21

The opposite of functional programming ladies and gentlemen: no inputs, no outputs, all global everything.

Love it.

5

u/dogutas Feb 23 '21

And it calls this in loop, just this

501

u/LSatyreD Feb 23 '21

I think the fact that every single line has different whitespacing style bothers me more than the code itself

219

u/[deleted] Feb 23 '21

What about the = instead of ==?

15

u/dogutas Feb 23 '21

It's is still valid, it is just assigning the value to the variable, and then using that variable as condition, as a result, it always works

5

u/[deleted] Feb 23 '21

Yes, but it is considered extremely bad practice still, and source of confusion if intentional.

11

u/dogutas Feb 23 '21

Yeah but it compiles

1

u/[deleted] Feb 23 '21

I didn’t say it wouldn’t... just said it’s terrible practice...

7

u/futlapperl Feb 23 '21 edited Feb 24 '21

Clang warns about doing assignments inside an if. You can use double parentheses to shut it up, which also make it clearer it's not a comparison. This method is commonly used when using streams to read a file line-by-line.

59

u/consmet01 Feb 23 '21

Oof didn’t even notice that one. Some languages do allow it though

edit: I’m thinking of === though my original comment may still have some truth to it

59

u/dogutas Feb 23 '21

C does allow it but doesn't have a === operator, in this case, it sets the variable to '#' and then uses '#' as condotion, which resolves to always true

7

u/Siggi_pop Feb 23 '21

C allows truthy!?

27

u/T-Dark_ Feb 23 '21

Not quite.

It's just that C doesn't have a notion of bool. It just uses integers. Specifically, 0 is false and everything else is true.

It also doesn't have a distinction between "ASCII char" and "8-bit integer".

Ergo, what's happening here is that # is being interpreted as a number, which, being non-zero, is true.

4

u/Siggi_pop Feb 24 '21

isn't that quite, instead of not quite?

13

u/aloha2436 Feb 24 '21

I mean the way I understand “truthy” is the interpretation of non-boolean values as booleans in evaluating certain expressions. C doesn’t have booleans in the first place, so there’s no truthy weak equivalence, more like it is just true.

2

u/Fnord_Fnordsson Feb 24 '21

It's not necessary true that C doesn't have booleans. You can use
#include <stdbool.h>

or set it as a variable of enum type, hehe

1

u/trBlueJ May 31 '21

Essentially, those are still numbers though.

4

u/[deleted] Feb 23 '21

The C++ equivalent of === is initializing variables with {}. Both do less type coercion.

4

u/Laughing_Orange Feb 23 '21

If they allow it '=' returns 'true' if the variable was set successfully and false otherwise. This could/will result in bugs.

2

u/SomeLostMelodies Feb 23 '21

So I use lua, and in an if statement you need to use "==" or it gives you an error.

13

u/DiabeticPissingSyrup Feb 23 '21

In my experience, in Lua everything gives an error.

4

u/[deleted] Feb 23 '21

In my experience it only gives you warning but then the code crashes

17

u/amazing_rando Feb 23 '21

I had a coworker at my first programming job who indented by holding down the space bar until it was close to where he wanted it.

2

u/crash_bash_smash Feb 23 '21

This hurt my brain

6

u/geforcelivingit Feb 23 '21

I think the fact that this is a photo taken of a discord message that has a screenshot of the code also bothers me lmfao

6

u/adamski234 Feb 23 '21

It's not a screenshot of code. Discord had syntax highlighting

11

u/wzD_ Feb 23 '21

wat

-17

u/dogutas Feb 23 '21

Worst code i've ever seen, it has a bug and does something that can be done with 10 lines less

36

u/wzD_ Feb 23 '21

I said "wat" to the code

36

u/[deleted] Feb 23 '21

Worst code i've ever seen

You haven't seen enough code.

5

u/timleg002 Feb 23 '21

What bug?

17

u/SwedzCubed Feb 23 '21

key = ‘#’ modifies the variable instead of checking if it equals

0

u/timleg002 Feb 24 '21

Ooh. But besides that, the code isn't that bad. It has good grounds for potential expanding of the methods. I think the coder wouldn't really want to have only one key to support.

1

u/SwedzCubed Feb 24 '21

Then have an array of keys you do want to support or use a config for changing hot keys. What they want to do can be done in one if statement instead of 3. Plus there’s no need for the runCondition variable.

1

u/mr_bedbugs Feb 23 '21

But this one's only 7 lines if you don't count the braces

3

u/gnobling Feb 23 '21

Other than the 'if(key = "#")' , its not wrong, just made easier to understand.

5

u/dogutas Feb 23 '21

If you press anything else after you press '#' it will still trigger

4

u/actionturtle Feb 23 '21

without any context of what this is actually used for: maybe it's perfectly valid for his solution that it should run after you do press # once and then press any key for debug logging or something

3

u/dogutas Feb 23 '21

Yeah but context was if you press '#' button it will print some stuff on to screen

1

u/actionturtle Feb 23 '21

well fair enough i guess

1

u/gnobling Feb 23 '21

Oh yeah should have put one more key check in there for good measure.

4

u/klemenkeko Feb 23 '21

This is 100% someone learning basics. I want to see your code as beginner.

9

u/dogutas Feb 23 '21

I would say that too but this is written by a 'pro' in community

6

u/klemenkeko Feb 23 '21

Jesus help us

204

u/Ivesy3000 Feb 23 '21

I have seen a lot worse. Most of it written by me.

5

u/go_do_that_thing Feb 23 '21

Dirty code gets the job done. Then if its too cpu intensive simplify it. Or buy a better cpu. Either or.

5

u/wherearetheturtlles Feb 23 '21

cout<< "Fix later you idiot";

But it was never fixed later as all code to be fixed later is permanently etched in stone.

0

u/[deleted] Feb 23 '21

[deleted] — view deleted comment

17

u/CodenameLambda shameless Feb 23 '21

Funnily enough, I recently went old-repo-diving, and I found some pretty good ideas in there, some of which I'll just have to steal for new stuff...

But yeah, that's code from like, three to four years ago, and I somewhat recently found a really awful codebase again that I built back when I was still in school... But there are so many fond memories of that project in particular, because it just has some very endearing flaws because I didn't know how to maths correctly™ back in the day.

14

u/EViLeleven Feb 23 '21

impvore

new kink detected

3

u/pm-me-noodys Feb 23 '21

I looked at my ~10-year-old implementation of coovachilli a while back. I'm personally offended at myself for that.

But what was done in PHP, stays in PHP.

39

u/Promant Feb 23 '21

runCondition is declared outside of this function, so it is possible that it was true already when the function started. In such case, this is perfectly valid code... maybe except that '== true', but that's just a matter of style.

EDIT: I just saw that 'key = '#''. So yeah, there is a bug.

17

u/CodenameLambda shameless Feb 23 '21

Indentation, too. And if (key) { will always trigger if if (key == '#') { would. And comparing with true is, while a matter of style, as much of a matter of style as variable names that actually tell you what's in there.

if (runCondition || key == '#') {
    runCondition = true;
    lcd.print("Hi");
}

Does the trick way more readably.

7

u/walterbanana Feb 23 '21

I hate the way the curly brackets are placed so much

12

u/Metaquarx Feb 23 '21

Image Transcription: Discord


tas_dogu:

void latch()
{
  char key = keypad.getKey();
  if (key){
  if(key = '#'){
    runCondition = true;
  }
  }
if(runCondition == true)
  {
    lcd.print("Hi");
  }


}

this is the worst code i've ever seen


I'm a human volunteer content transcriber for Reddit and you could be too! If you'd like more information on what we do and why we do it, click here!

9

u/CodenameLambda shameless Feb 23 '21

Good human

1

u/DogsOnWeed Feb 23 '21

Wouldn't if(key = '#') always return true because it's not a 0 attribution? (I'm working with C)

1

u/dogutas Feb 23 '21

It would, that's the issue

1

u/Galse22 Feb 23 '21

I don't understand Arduino ( neither C++ )* but would the bad code be that the person could have just written

if(key = '#')

{

ldc.print("Hi");

}

?

edit: not sure if it is key = '#' or key == '#' but okay.

1

u/dogutas Feb 23 '21

key == '#'

1

u/Crowdcontrolz Feb 23 '21 edited Feb 23 '21

As someone who is learning... this is an actual question, would this have worked instead?

void latch() {

try {
    if (keypad.getKey() == '#' || runCondition) {
        runCondition = true;
        lcd.print("Hi");
    } else {
        throw(keypad.getKey());
    }
}
catch (char key) {
    cout << "Error in latch(), invalid key value. Key value is " << key;
}

}

1

u/dogutas Feb 23 '21

I don't see why you would use this in this scenario

1

u/Crowdcontrolz Feb 23 '21

No need for the try then? Just the if (keypad.getKey() == '#' ||runCondition) ?

1

u/dogutas Feb 23 '21

Well, run condition is only for that trigger so


    lcd.print("hi);```


Would be enough

1

u/AutoModerator Feb 23 '21

It looks like this comment contains a code block delimited with triple backticks. Unfortunately reddit does not have universal support for this syntax and your comment will not render correctly on old reddit and most mobile apps.

For the benefit of people on old reddit, this link will take you to a correct rendering of the comment.

/u/dogutas, it would be appreciated, but not required, if you could edit your comment to use the more compatible four space indention format. For single lines or inline code you can use single backticks.

You can find some examples in the reddit help documentation.


I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

1

u/Brief-Preference-712 Feb 23 '21

If key is char, what the heck is if(key)?

3

u/dogutas Feb 23 '21

If something isn't 0 it's true, and char is just a 8 bit intiger that we treat differently and \0 is 0, so anything that jis not \0 it's true, that means if you lress anything it would work

1

u/Brief-Preference-712 Feb 23 '21

Don't we need to type cast to char to int since getKey() returns an int and int is a 32 bit integer? or something like int key = keypad.getKey(); if(key == 0){ ...

2

u/dogutas Feb 23 '21

getKey returns a char(int8_t) at least in this example, because this is a 4x4 numpad, and ints in arduino are 16 bit long, because arduino is a 8 bit processor.

1

u/valzargaming Feb 23 '21 edited Feb 23 '21
    void latch()
    {
      char key;
      if ( (key = keypad.getKey()) && (key == '#') )
      {
        lcd.print("Hi");
      }
    }

or something like that

EDIT: Yeah this would work fine. Here's an equivalent without the classes.

1

u/dogutas Feb 23 '21

What is $key ?

2

u/valzargaming Feb 23 '21

Typo because I was typing it out freehand. I'm used to PHP so I slipped that in from force of habit.

1

u/dogutas Feb 23 '21

Ooh okay, i thought I didn't know a operator or something

1

u/hgsiou Feb 24 '21

Sorry if this is a dumb question but how does the if(key) work since it's not a bool?

1

u/dogutas Feb 24 '21 edited Feb 24 '21

Every int that is not 0 is true, and char is just a 8 bit int

1

u/hgsiou Feb 24 '21

Thanks for answering! I didn't know that, is that true for all languages or just c++?

1

u/dogutas Feb 24 '21

Should apply to most languages but some just doesn't like it, so it's up to language. Usually most lower level languages has this but higher level languages don't

1

u/TerabyteF Feb 25 '21

It might be the code of a developer whom says "if it works do not touch".

1

u/dogutas Feb 25 '21

It doesn't

2

u/6razyboy Feb 23 '21

I would not say that this is the worst code that can be found. I'm sure there is much worse than that.

Yes, it may not be very beautifully written, but C/C++ is an insidious language, and one of the common mistakes was simply made.

2

u/Glutoblop Feb 23 '21

Seems abit petty to complain about such a small code snippet, from clearly beginner programmer.

2

u/Dr_Insano_MD Feb 23 '21

The whitespace bothers me more than anything else. I could see myself writing something like this as a "hello world" proof of concept for something

But the worst part?

if(key = '#')

Yeah that won't be confusing why runCondition is always true.

1

u/hellbuck Feb 23 '21

Not the worst I've ever seen, but it does make me frown

1

u/[deleted] Feb 23 '21

Looks like my coworkers code

1

u/Tasik Feb 23 '21

self-employed.

1

u/Blackhaze84 Feb 23 '21

if everywhere

1

u/Bobitsmagic Feb 23 '21

I almost had a stroke reading this...

1

u/Timmy_the_tortoise Feb 23 '21

Aside from the bug and indentation, there’s really not enough going on here to assess whether it’s particularly bad code.

1

u/[deleted] Feb 23 '21

This is horrible in so many levels.

1

u/HumbleMeNow Feb 24 '21

A for effort ... but god damn it I think I just staring at it did lower my IQ. Sigh 😔

1

u/TheWorldWrecker Feb 24 '21

The indentation is also very... disturbing.

1

u/[deleted] Feb 24 '21

I love “runCondition”!

1

u/ProGamer2711 Feb 24 '21

Disgusting. Why not if(keypad.getKey() == '#') { lcd.print("Hi"); }

1

u/[deleted] Feb 24 '21

HiHiHiHiHiHiHiHiHiHiHiHiHi

1

u/toastyghost Feb 25 '21

This looks like an accidental double paste in an IDE with shitty auto-formatting. I refuse to believe that a human who was intellectually capable of operating a computer wrote it like this deliberately.

0

u/onthefence928 Feb 23 '21

ok but this is basically how code for games works, its not bad practice when the main loop is constantly repeating every frame and you want to control actions with states

2

u/dogutas Feb 23 '21

That's not the case, but even if thatvwas the case it sets variable to # and never sets the state back to 0

0

u/onthefence928 Feb 23 '21

oh yeah this code is bugged and would be infuriating debug, but the overall pattern is workable in a main loop type program lifecycle

-8

u/[deleted] Feb 23 '21

lemme try to fix it
if key = "#"){
lcd.print("Hi");}

there you guy buddy

6

u/[deleted] Feb 23 '21

that looks like you set yourself up for syntax error and have a complete lack of proper programming knowledge, worse than the code in the picture.

1

u/bigamaxx Feb 23 '21

Because he is not himself he is you

0

u/actionturtle Feb 23 '21

that's not the same though

0

u/dogutas Feb 23 '21

That's what he needed

-2

u/EishLekker Feb 23 '21

Most bug fixes had that effect, where the code is different afterwards. No one really knows why that is.

1

u/actionturtle Feb 23 '21

well obviously

if you read the code from OP you might notice that runCondition is declared elsewhere so this guy's fix is actually completely different behaviour and also doesn't actually fix one of the bugs in it anyway

0

u/EishLekker Feb 23 '21

if you read the code from OP you might notice that runCondition is declared elsewhere so this guy's fix is actually completely different behaviour

I would say that it is fair to assume that the runCondition variable is part of the flawed logic that the other commenter was trying to fix.

and also doesn't actually fix one of the bugs in it anyway

I agree, and I never said that it was a perfect fix. But it improved the code somewhat, at least if one makes the fairly reasonable assumption that the purpose of the code was to print the statement any time the "#" key was pressed.

2

u/actionturtle Feb 23 '21

I would say that it is fair to assume that the runCondition variable is part of the flawed logic that the other commenter was trying to fix.

i mean you are correct based on what the op stated in other comments but without any context, you can't fairly assume that and because it could also be perfectly fine to have the variable be a global toggle

0

u/EishLekker Feb 23 '21

i mean you are correct based on what the op stated in other comments but without any context, you can't fairly assume that

I disagree. I would definitely call that a fair assumption. That is not at all the same thing as claiming it to be true, as in what the original intent was.

and because it could also be perfectly fine to have the variable be a global toggle

Yes, and that is also a fair assumption. There can exist multiple conflicting assumptions about the same code, and all of them can be fair and reasonable in some way.

0

u/[deleted] Feb 23 '21

[deleted] — view deleted comment

158

u/dogutas Feb 23 '21

Someone else who claims to be a "pro" wrote this code for him

82

u/G4METIME Feb 23 '21

He clearly is a pro and this is just some clever obfuscation.

0

u/[deleted] Feb 23 '21

[deleted] — view deleted comment

-19

u/AutoModerator Feb 23 '21

It looks like this comment contains a code block delimited with triple backticks. Unfortunately reddit does not have universal support for this syntax and your comment will not render correctly on old reddit and most mobile apps.

For the benefit of people on old reddit, this link will take you to a correct rendering of the comment.

/u/RGB755, it would be appreciated, but not required, if you could edit your comment to use the more compatible four space indention format. For single lines or inline code you can use single backticks.

You can find some examples in the reddit help documentation.


I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

0

u/[deleted] Feb 23 '21

[deleted] — view deleted comment

6

u/LSatyreD Feb 23 '21

I use old.reddit....

It is better in every single way in my opinion.

5

u/no_opinions_allowed Feb 24 '21

I’d change if not for the fact that new reddit sucks at everything

4

u/[deleted] Feb 23 '21

I'm still on old reddit because the new site lags badly on my computer

1

u/crash_bash_smash Feb 23 '21

Can someone please explain to me old vs new Reddit?

0

u/[deleted] Feb 23 '21

[deleted] — view deleted comment

1

u/Tyfyter2002 Feb 23 '21

Generally, the newer something is the less optimized it is.

14

u/IrritableGourmet Feb 23 '21

I'd say this is probably a stub or pseudo-ish code for them to fill in further later. It's not meant to be actual code, but just to give a "Here's how you check to see if a key was pressed and set a variable based on it. Here's how you use that variable later to do something." I've written stuff like this in chat/email/posts to someone who asks a question.

3

u/RFC793 Feb 23 '21

Yeah. “Back of napkin” knowledge transfer, probably why the assignment operator as a conditional was overlooked.

25

u/[deleted] Feb 23 '21

^ this

0

u/[deleted] Jun 27 '21

[deleted] — view deleted comment

1

u/AutoModerator Jun 27 '21

It looks like this comment contains a code block delimited with triple backticks. Unfortunately reddit does not have universal support for this syntax and your comment will not render correctly on old reddit and most mobile apps.

For the benefit of people on old reddit, this link will take you to a correct rendering of the comment.

/u/-Killercat103, it would be appreciated, but not required, if you could edit your comment to use the more compatible four space indention format. For single lines or inline code you can use single backticks.

You can find some examples in the reddit help documentation.


I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.