r/badcode • • Aug 16 '20

c++ Another function to see if something is even or not

Post image
1.0k Upvotes

82 comments sorted by

96

u/Bliztle Aug 16 '20

Does this even compile? Seeing as the program probably doesn't know the if statements account for all values, wouldn't this say "not all code paths return a value"?

79

u/rs277_ Aug 16 '20

It compiled, but with a warning I didn't seem to understand until this comment

20

u/MachineGunPablo Aug 17 '20

Use -Werror and -Wall kids

38

u/[deleted] Aug 16 '20

I think it depends on the compiler. (don’t quote me on this) But technically the ifs encapsulate all possibilities. The int is either < 0 or >= 0. So, all code paths do return a value. I believe (idk for sure tho? I haven’t worked with C++ in a few years) some compilers may allow this.

25

u/LordOfDemise Aug 16 '20

It'd be a lot easier for the compiler to figure that out if the second if statement were replaced with an else clause of the first if

12

u/[deleted] Aug 16 '20

I guess there’s a reason we’re in r/badcode rn

7

u/StuntHacks Aug 16 '20

GCC allows this although it throws a warning. Checking if all ifs encapsulate every possible option is too much effort, and especially for large if-structures rather unfeasible. If the last branch is an else, it compiles without a warning.

2

u/Mr2-1782Man Aug 17 '20

It does depend on the compiler. A smarter compiler will see that input is never changed and that the two conditions are opposite. So one or the other will end up returning. A simpler compiler won't make those determinations.

Fun Fact: If a smart compiler can in fact determine that a code path does something undefined or ambiguous it'll just have the function return 0 or some other constant value.

4

u/MachineGunPablo Aug 17 '20

In C/C++ not returning from a non-void function is actually not an error. Most compilers will give you a warning, though.

1

u/Bliztle Aug 17 '20

Ah okay, i only use C# which doesn't allow this, so assumed other C languages would be the same

1

u/MachineGunPablo Aug 17 '20

Seems like this is C++, if so it's a warning not an error

1

u/[deleted] Aug 17 '20

Just change the second if to an else

0

u/[deleted] Aug 16 '20

[deleted]

2

u/printers_suck Aug 17 '20

Linters will throw a big red on that though

3

u/dashingThroughSnow12 Aug 17 '20

Which is good because it matches the rest of my code.

2

u/DiscreteNotDiscreet Aug 16 '20

Does this even work?

1

u/rs277_ Aug 16 '20

It seemed to work for me, even with negative numbers

103

u/sekex Aug 16 '20 edited Aug 16 '20

Could actually be more efficient for small values than doing a modulo on the absolute value considering a division can take up to 80 cycles. (don't quote me on this)

Edit: It's actually a division by 2, so a simple bitshift (<<) would do in 1 cycle

121

u/xVirusHDx Aug 16 '20

aight I’ll quote you in my graduation paper

48

u/StuntHacks Aug 16 '20

As is common knowledge, a division can take up to 80 cycles. 1 This means it can be concluded that the given code would be more efficient under the right circumstances when compared to traditional methods (namely the modulo-operation), and should therefore not be considered to be produced by a master of Italian cuisine.

1 /u/sekex, on reddit.com (accessed 16th of August, 2020)

55

u/damyvv Aug 16 '20

Even better, modulo 2 is the same as just checking the last bit. So even a bitshift is not necessary to check if a number is even. A simple 'and' instruction is all that it takes.

23

u/nuephelkystikon Aug 16 '20

Modulo 2 typically gets compiled into that.

9

u/sekex Aug 16 '20

That's true, didn't think about it

6

u/futlapperl Aug 17 '20

bUt WhAt iF yOuR plAtfOrM uSes BasE 3?!

17

u/Timmy_the_tortoise Aug 16 '20

Most compilers would do that optimisation for division by 2 (or powers thereof) automatically as well.

6

u/[deleted] Aug 16 '20

Simple &1 will give 0 if even and 1 if input is odd.

4

u/[deleted] Aug 16 '20

Even so, would that efficiency really make enough of a difference to justify this?

11

u/sekex Aug 16 '20

Depends on your industry. In HPC/HFT/video games, definitely. Furthermore if you have to run this task billions of time, a 40 times speed gain makes a huge difference (hours vs days.)

2

u/[deleted] Aug 16 '20

Fair enough, but doesn’t it also depend on the input here? I mean I guess it’s only O(n), but if the input is 183673827199181...

Edit: nevermind I realized you said for small values, but I would still say that you would really need to justify this and know that the values would always be small.

11

u/sekex Aug 16 '20

Someone in the comments pointed out that you could just write !(a & 1) as you only need to look at the last bit

1

u/[deleted] Aug 16 '20

There’s always a better way I suppose

2

u/[deleted] Aug 17 '20

tbh a decent compiler would notice this and fix it in the compilation.

10

u/Ma_124 Aug 16 '20 edited Aug 16 '20

Worst thing is that the compiler doesn't even optimize it: https://godbolt.org/z/G7r3dT

5

u/redditsoaddicting Aug 16 '20

You didn't even use any optimization flags. However, Clang seems to optimize it a bit more with flags.

5

u/Ma_124 Aug 16 '20

I'm sorry. I'm not very experienced with gcc and thought optimization was enabled by default but even with -O3 it doesn't seem to optimize the loop away. But if you still think that I missed a flag feel free to comment and I'll amend my comment.

4

u/Mr2-1782Man Aug 17 '20

Compiler optimizations and why or why they don't happen aren't immediately obvious. My suspicion is that gcc only optimizes away a loop if the number of iterations is known at compile time. In my experience clang does a better job of working out the math and figuring it out.

1

u/AugustinCauchy Aug 16 '20

Try moving the return to the end of the function, clang goes completely ballistic.

2

u/redditsoaddicting Aug 16 '20

Nice, it looks a little bit better with -mno-sse but it's still pretty bad lol

2

u/Mr2-1782Man Aug 17 '20

I think that's because clang isn't doing a def/use check on input so its treating them as separate loops and unrolling them.

18

u/cthulhu_is_right Aug 16 '20

Gotta admit, a lot of my code prob belongs here

4

u/OptimalMain Aug 16 '20

Probably my hacks too.. But at least I knew I could do modulo 2.

Learned a new trick with just checking the least significant bit though!

25

u/Astrokiwi Aug 16 '20

Would something like !(input && 0x00000001) work?

33

u/Timmy_the_tortoise Aug 16 '20 edited Aug 16 '20

In C++ && is a Boolean operator, what you’re looking for is & which would perform a bit wise AND, which would indeed work. Not sure why you got downvoted for not much more than a typo... perfectly decent solution. Possibly the most optimal, though a good compiler would probably optimise % 2 to the same operation anyway.

8

u/Astrokiwi Aug 16 '20

I think people are assuming I've been whooshed and am actually trying to correct OP.

And yeah, you're right, 0x00000001 evaluates to true, so with my mistake!(input && 0x00000001) reduces to !input.

5

u/Evy1123 Aug 16 '20

O(N) isEven. I love it.

3

u/DarthPiotr Aug 16 '20

I think it's high time when someone should make an API for this. Why do we have to code it ourselves? /s

15

u/Luca_G12 Aug 16 '20

Why is it always the even check its like the most simple thing

17

u/fuckingaccount69 Aug 16 '20

thats not the point

1

u/HerissonMignion Aug 16 '20

The point is how can you do it the worst way.

5

u/stable_maple Aug 16 '20

WHy NoT A MoD?!?

1

u/das_Keks Aug 16 '20 edited Aug 16 '20

Negative part should use i-- As it is, it's an infinite loop for negative numbers.

EDIT: I'm an idiot, if it's negative of course we have to count "up".

3

u/rs277_ Aug 16 '20

It doesn't, I made the loop count up from the input number towards 0, It's just written differently than most loops, but I found this more convenient

2

u/das_Keks Aug 16 '20

Oh, you're right. ^^'

2

u/g30r93g Aug 16 '20

bro ever heard of modulo??

2

u/[deleted] Aug 16 '20

it might be bad, but its hella inventive!

2

u/[deleted] Aug 17 '20

if only there was a mathematical operation for this

2

u/l3njo Aug 17 '20

I'm not even mad. This is art.

2

u/Lionry Aug 17 '20

haha num % 2 go brrrrr

2

u/Neat-Flatworm7025 Oct 29 '20

The first way I checked if a integer was even or odd was to convert to float, the divide by two, then convert to string, then loop through the string to check for a decimal place.

2

u/[deleted] Aug 16 '20

inline bool isEven(int input) { return input & 1; }

1

u/WeAllWantToBeHappy Aug 17 '20

Doesn't work as good as the OP's version.

1

u/Abangranga Aug 16 '20

Ruby allows for concise solutions to the even number problem oppressing the progress of humanity. For example:

def highly_technical_is_even?(input, counter = 0)
    if input.zero?
        return (counter % 2).zero?
    else
        highly_technical_is_even?(input - 1, counter + 1)
    end
end

def equality_is_even?(input)
    ((input / 2) * 2) == input
end

1

u/HerissonMignion Aug 16 '20

bool isEven(int num) { return num == num / 2 * 2; }

1

u/badadvice4all Aug 17 '20

Not far off from how I would probably do it.

1

u/throwaway8u3sH0 Aug 17 '20

Needs more recursion.

0

u/rowbiin Aug 16 '20

Actually smart! That’s a bright future, right there

0

u/nati9931 Nov 02 '20

ugh. return (number % 2 == 0);

-2

u/RovingRaft Aug 16 '20

if(input % 2 == 0)

-2

u/walterbanana Aug 17 '20

return value % 2 == 0

-3

u/myevillaugh C# Aug 16 '20

It should be an else if. And both returns should be replaced with a return statement outside of the if block. http://imgur.com/gallery/euRu9De

4

u/rs277_ Aug 16 '20

Nah not here, this is r/badcode

0

u/[deleted] Aug 16 '20

[deleted]

24

u/cant-find-user-name Aug 16 '20

That's the joke.

11

u/NetherFX Aug 16 '20

It's a running gag

0

u/[deleted] Aug 16 '20

[deleted]

19

u/Lysdal Aug 16 '20

damn you're so smart how did you come to with that, such a shame the op didn't realize it was that simple!

1

u/[deleted] Aug 16 '20

Holy fucking shit the downvotes

1

u/jess-sch Aug 16 '20

actually it's x&1==0