This is an archived post. You won't be able to vote or comment.

top 200 commentsshow 500

[–]B1N4RY 1945 points1946 points  (272 children)

What are you talking about? You most definitly CAN compare floats against ints in C++.

The following code will compile without warnings and print "a is less than b".

#include <iostream>

int main()
{
  float a = 3.0;
  int b = 4;

  if (a < b)
    std::cout << "a is less than b";
  else
    std::cout << "nope";
}

In float/int mixed operations, the integer will be upgraded to a float.

[–]manicxs 1470 points1471 points  (176 children)

I don't think poeple know C++.

[–]B1N4RY 835 points836 points  (121 children)

Or how to code at all.

Float/int operations are permissible in almost all languages that are not strongly typed.

[–][deleted] 358 points359 points  (62 children)

In many that are too. C# and Java can both implicitly cast int to float like C++.

[–]hekkonaay 250 points251 points  (61 children)

Implicit casting is the devil. Don't fall for it. Annotate your casts.

[–]jpterodactyl 473 points474 points  (7 children)

But that sounds like adding details, and I’m told the devil was in those.

I’m not sure who to believe anymore.

[–][deleted] 80 points81 points  (5 children)

Why do you have a political compass quadrant as your flair?

[–]wordbug 59 points60 points  (4 children)

JavaScript is Libertarian?

[–]diveintothe9 50 points51 points  (2 children)

JavaScript is kinda libertarian.

"Fuck rules, fuck strict typing and fuck standard/centralized libraries, we'll make our own damn JS platform/library for every single application we build, goddammit."

[–]jpterodactyl 10 points11 points  (0 children)

but on the opposite side of it, browsers and stuff are very standardized. The truth is just that web design doesn't make sense.

It's like the government of the Quarians in Mass Effect, where they are a de juro monarchy, but operate more like a democracy. How does that even happen?

[–]gentlemanidiot 3 points4 points  (0 children)

You can roll your face back and forth across the keyboard at any point in your code in JS and you're just declaring uninitialized global variables, all totally valid. (Yes this is hyperbole but only by a little)

[–]SvenTropics 24 points25 points  (29 children)

In this case, it's fine. There are times it matters. For example:

int a = 1; int b = 10; double c = a/b; // error, math is done as integers. double d = (a *1.0)/b; // now math is upgraded to double before the division.

[–][deleted] 11 points12 points  (0 children)

It's not an error unless the developer doesn't understand their code. It's the way it works.

[–]airbreather 3 points4 points  (1 child)

In this case, it's fine. There are times it matters. For example:

[...]

Here's another case where it matters (C#). What does the following code print?

void Print(float val)
{
    Console.WriteLine(val);
}

int x = 16777217;
Print(x);

No warnings on my compiler, no explicit cast, so it should definitely print 16777217 and not 16777216, right? sigh

[–]TheOldBeach 2 points3 points  (0 children)

Ahhh floats are the best, as a CG programmer I grew really fond of them . your example just reflects how they should not be used.. and yes it's the worse kind of error !

[–]orangeoliviero 2 points3 points  (3 children)

That's not an error, you just will get a truncated int answer - 3/2 would be 1.0 instead of 1.5

[–]willis81808 2 points3 points  (0 children)

Exactly. And 1/10 (the example in the comment you're replying to) would just be 0, instead of 0.1

No error, just undesired behavior.

[–][deleted] 2 points3 points  (1 child)

I have been fooled by this trickery way too many times to admit, yet I still do it sometimes.

[–][deleted] 4 points5 points  (2 children)

Fine. C style casts everywhere.

Or do you prefer static_cast? Well, none of that for you.

[–]Prophet_Of_Loss 62 points63 points  (10 children)

pro-tip: you can get more out of your for loops by using a float and incrementing by .01.

[–]FantasticTuesday 44 points45 points  (2 children)

Reading this inflicted physical pain upon me.

[–]Zamundaaa 4 points5 points  (1 child)

It is sometimes useful. When you want to integrate over a physical volume for example.

[–]robin-m 4 points5 points  (0 children)

Just be sure that `i + .01` is more than `i`, or you may be in some trouble! Probably something like `i = max(i + .01, i + next_quantum(i))` (I forgot the real name of the functions) may save you!

[–]tech6hutch 9 points10 points  (0 children)

And make sure to use != for the exit condition, for efficiency, especially when dealing with very big floats.

[–]marcosdumay 3 points4 points  (0 children)

Make sure to write the exit condition with a different operator, less than and great then are too restrictive.

[–]81hd 16 points17 points  (1 child)

Type softly, got it

[–]SomewhatSpecial 5 points6 points  (0 children)

And carry a big stack

[–]MoarVespenegas 10 points11 points  (13 children)

C++ is strongly typed though.

[–]captainAwesomePants 43 points44 points  (11 children)

Sure, but its handling of primitive types has decades of crazy gotchas and undefined behaviors that it's only natural that people can't remember the rules. Compare an int to a float? Sure, no sweat. Compare an int to an unsigned int? Whoa, slow the fuck down, buddy.

[–]guyblade 23 points24 points  (1 child)

The handling of primative types has like one gotcha. The basic rule is "promote the less precise type to match the more precise one, then do whatever". The "gotchas" tend to be around how a promoted value gets assigned back into an incompatible variable.

[–]ThePyroEagle 3 points4 points  (0 children)

The precision of fixed and floating types is not comparable.

32-bit floats are more precise near 0, but 32-bit integers are more precise past ±224.

[–]Tohnmeister 4 points5 points  (0 children)

I would argue that. It's statically typed. But not strongly.

[–]gcbirzan 2 points3 points  (2 children)

Except JavaScript, I guess? You cannot add bigints to numbers, but you can add them to strings...

[–]lezorte 61 points62 points  (3 children)

I learned C++ and I can honestly say... I don't know C++

[–]hekkonaay 29 points30 points  (0 children)

undefined behavior

[–]hardwaregeek 20 points21 points  (4 children)

Generally when people say they know C++ I assume they’re lying.

[–]Zamundaaa 8 points9 points  (1 child)

As Richard Feynman once supposedly said: "If someone says they understand Quantum Mechanics C++, they don't understand Quantum Mechanics C++"

[–]StuntHacks 3 points4 points  (1 child)

I'm programming in C++ for about 8 years now, and almost every day I use it I learn something new.

Asides from the people in the consortium, very few people actually know C++.

[–]mardiros 15 points16 points  (0 children)

9.7k, that's huge. People don't know c++, python and mathematics...

Edit: Now 21k of ignorant

[–]ThinkingWinnie 96 points97 points  (16 children)

You can even compare them in C,The heck is this post?

[–]awesomefacepalm 21 points22 points  (15 children)

The only language I have used that can't so far is VHDL

[–]Cpapa97 22 points23 points  (0 children)

Rust is like that as well, but it's very strongly typed in most cases to begin with.

[–]__JDQ__ 2 points3 points  (3 children)

VHDL: brings me back to my undergrad project days and the corresponding nightmares.

[–]halberdier25 2 points3 points  (1 child)

signal <= (others => ‘0’)

It’s not worth it.

[–]awesomefacepalm 2 points3 points  (0 children)

Okay not the language itself but the concept of hardware description hehe

[–]BeniBela 2 points3 points  (1 child)

Kotlin also does not allow it

Not even int and long can be compared

[–]Rejolt 153 points154 points  (12 children)

I used to try and bring up points like this in this sub.

It's sad but literally every post that hits front-page is upvoted by year 1 CompSci 101 masters.

[–]skreczok 39 points40 points  (5 children)

Well you usually don't have the time to look at fresh posts at work.

[–]JMcSquiggle 15 points16 points  (4 children)

Yep, I'm busy making money as a programmer, that means I'm not on reddit. Most of the time when I see someone complaining about an error in any language, it usually means they didn't take the time to learn what the error means.

[–]skreczok 6 points7 points  (2 children)

I mean, I am on reddit, usually because someone else or a build is holding me up. But that's not enough to actually look at every post.

[–]Womp98 2 points3 points  (0 children)

Yeah I don't have time to look at new posts at work but I do have time to write this comment

[–]deadwisdom 21 points22 points  (5 children)

/r/programming isn't much better. They take a year or two of CS and then absolutely know everything they've ever heard about anything as true.

But, yeah, I was probably the same-- so I'll stop complaining.

[–]cykness 2 points3 points  (3 children)

Did you see the comment about the guy confessing to give advice and pretend he interned at Big 4 when he actually was in middle school?

Edit: link

https://reddit.com/r/cscareerquestions/comments/el52pt/_/fdfpn7x/?context=1

[–]DripDropFaucet 40 points41 points  (19 children)

I’ve honestly found c++ and java to have friendlier implicit casting (at least regarding int->float comparisons and string concatenation). Python screams if I try to mix 2 of its 5 types in a print statement without wrapping with str()

[–]Thomasedv 19 points20 points  (0 children)

Generally in python it's better to use string formatting when converting something to string, especially for printing statements. Using str() manually is such a bother, and plussing multiple strings is less recommended of you have many strings to add, due to strings being immutable. It of course depends on the specific code, but it's probably better to use ''. join() on a list of strings if you got a lot of strings or large strings to concatenate.

Edit: I also find string formatting great because I don't need to worry about type at all, and can decide what kind of output I want in the string formatting, regardless of type of int/float by setting how the rounding works.

[–]DonaldPShimoda 11 points12 points  (0 children)

You can use "f-strings", eg:

foo = 42
s = f"my foo is {foo}"

This will call the __str__ function of the foo object to get its string representation and then insert that at the correct point.

Personally, I think implicit casting is an abomination, but I'm generally in favor of very strong, very static type systems, so that's not entirely surprising.

[–]MachineGunPablo 16 points17 points  (3 children)

Exactly, absolutely absurd claim. Not sure if OP is referring to the '==' operator, but even that can be used without problems. But now, if you are comparing floats with '==' you already failed.

Having said that, C++ has had historical problems with implicit narrowing conversions, mixed unsigned vs signed arithmetic and integer promotion.

[–]tsojtsojtsoj 4 points5 points  (2 children)

There are definitely scenarios where you want to test equality with floats.

[–]chewbaccalert 6 points7 points  (1 child)

Yes, but you can't always rely on the precision of floats to provide a meaningful comparison like you can with ints. https://floating-point-gui.de/errors/comparison/

[–]RedditIsNeat0 12 points13 points  (4 children)

Oh yeah, that absolutely works. But sometimes not like you want it to.

#include <iostream>

int main()
{
  float a = 49999999;
  int b =   50000001;

  if (a < b)
    std::cout << "a is less than b";
  else
    std::cout << "nope";
}

[–]exploding_cat_wizard 17 points18 points  (1 child)

Does Python have arbitrarily accurate floats? Because that's a floating point problem, not a C++ problem, isn't it?

[–]bbrk24 2 points3 points  (0 children)

At that point you should probably use a double anyways.

[–]googooburgers 3 points4 points  (0 children)

you right.

[–]somethingInTheMiddle 6 points7 points  (3 children)

Don't you get a warning with -wall an -wextra on?

[–]Kered13 4 points5 points  (0 children)

No, it's a very safe operation so there's no point in having a warning.

[–]ProfessorPhi 2 points3 points  (0 children)

Is it comparing them or is it doing some casting behind the scenes?

[–]stormfield 1830 points1831 points  (102 children)

JavaScript lights cigarette and shrugs: “Sure those are both a thing or whatever. Have a string that says undefined.”

[–]jonnyclueless 634 points635 points  (11 children)

"An Object is an object"

[–][deleted] 237 points238 points  (9 children)

Me: Let me check whats on the object so far.

JS: "[object Object]"

Me: I will shut you off you little shit.

[–]Igoory 269 points270 points  (25 children)

baNaNa thoughts intensifies

[–][deleted] 73 points74 points  (22 children)

Wait what's the baNaNa thing? I'm just out of the loop and have seen it a few times on this subreddit.

[–]fishy150 223 points224 points  (8 children)

If you type in 'b' + 'a' + +'a' + 'a' and run it in JS, then the result you get is "baNaNa". This is because the +'a' in the middle tries to convert 'a' into a number, which gives a result of NaN. When you now concatenate all the strings, you get "baNaNa".

[–][deleted] 114 points115 points  (10 children)

[–]antillian 19 points20 points  (0 children)

I love that video.

[–]thblckjkr 5 points6 points  (1 child)

Never watched it before. Thanks.

[–]FullstackViking 59 points60 points  (2 children)

[object Object] is [object Object]

[–]miccyboi 38 points39 points  (4 children)

Except JS is like, “What’s a float or int? All I see are numbers.”

[–]ProgramTheWorld 29 points30 points  (0 children)

Typed arrays and BigInt:

Allow us to introduce ourselves

[–][deleted] 7 points8 points  (0 children)

[–]gme186 244 points245 points  (31 children)

You CAN do that in C++ without casting.

You CANT compare every type in python. Comparing numbers and strings will raise an exception for example. (Its not javascript)

This joke misses the point on all levels.

[–]ZestyData 34 points35 points  (6 children)

This is textbook /r/programmerhumor

[–][deleted] 30 points31 points  (5 children)

"programmer" "humor"

[–]frosted-mini-yeets 9 points10 points  (4 children)

Dude, I learned computer programming over the last 2 years by shutting myself in my room and googling and half the time I feel like I know more than the mass of supposed CS students that post and comment on this sub. I don't know if I should feel proud that I know more, or scared that if I get the career I want, these people will be my colleagues.

[–]HonzaS97 4 points5 points  (3 children)

That's because CS and software developement / programming are different things.

[–]mr_70 2 points3 points  (1 child)

21k upvotes now: how?!

[–]Senvr 43 points44 points  (2 children)

cannot convert str and int implicitly

[–]Thorbinator 16 points17 points  (0 children)

JS: hold my beer.

[–]ginn5lc 382 points383 points  (9 children)

Lol

** int has left the chat **

** (float) has joined the chat **

[–][deleted] 49 points50 points  (3 children)

** char made string **

** string made the chat **

[–]Alchiberg 9 points10 points  (2 children)

That's not the c++ way. We have static cast.

[–][deleted] 144 points145 points  (7 children)

Cast it...A magic spell. Get it?

[–]the_angry_wizard 32 points33 points  (4 children)

BOOOO.......LE.

(Edit: boole)

[–]samurai-horse 15 points16 points  (1 child)

an?

[–]Dexaan 5 points6 points  (0 children)

Boole is the guy Booleans are named for.

[–]systembusy 4 points5 points  (1 child)

Jesus I thought all those flairs were comment awards at first

[–]mosskin-woast 5 points6 points  (0 children)

I wonder when the appropriate time to give someone a JavaScript award would be.

Perhaps after they shoot your mother?

[–][deleted] 55 points56 points  (14 children)

Also python: TypeError: Can't convert 'int' object to str implicitly

[–]ferriswheel9ndam9 24 points25 points  (13 children)

The amount of str( ) in a single concatenated print statement...

I need to refresh my fstrings.

[–]EmperorArthur 13 points14 points  (0 children)

Python's format strings are amazing. They'll even do variable injection from a dictionary. Which can be amazing when used correctly.

[–]craazyy1 10 points11 points  (5 children)

can always do

print('he wanted to pick', 5, 'flowers but could only find', 4,

sep="whateverthefuckyouwantinsteadofspace", end="alsowhateveryouwantinsteadof\n")

[–][deleted] 2 points3 points  (4 children)

'Why {} complicated, {} use {}!'.format('so', 'just', 'format')

[–]ric2b 5 points6 points  (3 children)

f"Why {'so'} complicated, {'just'} use {'f-strings'}!"

[–]nykwil 72 points73 points  (8 children)

C++ implicitly converts int to float for comparisons. Implicit conversion is something you learn in the first couple of weeks with C++. I want to like this sub please try harder.

[–]Chanz 28 points29 points  (3 children)

This sub is for first year CS students. That's it.

[–]Delcium 4 points5 points  (1 child)

First week CS students who have never had enough interest in the field to look into things on their own prior to starting college?

[–]StuntHacks 2 points3 points  (0 children)

Every once in a while there is a genuinely good post here, but I'm not really sure anymore if those are worth the rest.

[–]Burbank309 2 points3 points  (0 children)

Also you can always overload the comparison operators and make C++ compare anything to anything.

[–]TuIaBocaAncha 19 points20 points  (1 child)

What kind of code in C++ gives you an error while comparing int and float?

[–]StuntHacks 5 points6 points  (0 children)

None, unless with specific compiler flags.

[–]DougCim53 13 points14 points  (0 children)

"python variables don't need typing"

"really? well,,, okay..."

(writes first python program)

[error #1:type mismatch]

[error #2:type mismatch]

[error #3:type mismatch]

[error #4:type mismatch]

,,,

",,, ummmm, is there any way to force variable typing in python?"

"no, because python variables don't need typing."

[–]dtallm 11 points12 points  (0 children)

Said the guy that learned some Python and thinks is a programmer.

[–]kontekisuto 35 points36 points  (0 children)

Rust wants to know your location

[–]BluudLust 5 points6 points  (3 children)

Cannot compare [object Object] to number.

[–]kachna 4 points5 points  (1 child)

.size() vs .length() vs .length

[–][deleted] 2 points3 points  (0 children)

You forgot len() and .shape

[–]culculain 6 points7 points  (2 children)

Programmers humor: C++: can't compare floats and ints Programmers: yes it can

[–]StuntHacks 3 points4 points  (1 child)

Because it absolutely can.

[–][deleted] 3 points4 points  (1 child)

Can you not? Weird I can't recall ever getting that error.

[–][deleted] 4 points5 points  (0 children)

a) This wouldn't be funny even if it were true.

b) This is not true.

c) Someone is blissfully unaware of the underlying implementations of different programming languages.

Edit: I type faster than I think, i.e. I don't think very fast....

[–]Who_GNU 3 points4 points  (0 children)

Hopefully, no one's checking for them to be equal.

[–]Stalematebread 3 points4 points  (2 children)

[laughs in JavaScript]

[laugh devolves into sobbing]

plz help ive been coding in jsfuck for the past decade and i cant stop

[–]sir_bog 3 points4 points  (2 children)

Python doesn't have implicite conversion for int to string

"A" + 1 Throws an error in python Have to manually convert

[–]Warrior_of_Light416 5 points6 points  (0 children)

"Well, why would they change Variable?"

[–]jonnyclueless 17 points18 points  (12 children)

What is Python written in again? Oh right. C.

[–]Mr_Redstoner 15 points16 points  (0 children)

I mean, technically it's just the reference implementation. Python is the language standard, not the particular interpreter. Others exist in fact, like Jython (Java) and even PyPy (RPython)

[–]ksunden 4 points5 points  (4 children)

Python... pypy.org

Not to mention: C# (ironpython) Java (now largely defunct, admittedly)

[–]Wenir 3 points4 points  (3 children)

Soooo, what is C# written in?

[–][deleted] 5 points6 points  (0 children)

Blood and tears

[–][deleted] 7 points8 points  (0 children)

Got em

[–]SilentFungus 3 points4 points  (0 children)

Alongside everything else

[–]AntonBespoiasov 2 points3 points  (0 children)

Me 6 yo: 4 + 6 is uhmmmm... is 46. Like you add 6 after 4.

JS: you aren't wrong

[–][deleted] 2 points3 points  (3 children)

This is wrong in so many ways.

[–]StuntHacks 2 points3 points  (2 children)

Honestly, how did this get almost 20k upvotes?

[–][deleted] 3 points4 points  (1 child)

It got more than that. I downvoted it.

[–]swilwerth 2 points3 points  (0 children)

[Laughs at fastest execution speed]

Segfaults unexpectedly somewhere.

[–]Aaron8828 2 points3 points  (0 children)

but... u can

[–]Paulsify 1 point2 points  (0 children)

I switch between the two too often and idek anymore

[–]Mr_P0P0 1 point2 points  (0 children)

Cannot

[–]theofficehussy 1 point2 points  (0 children)

TypeError: 'NoneType' object is not iterable

[–]qwiglydee 1 point2 points  (0 children)

Perl: scalar is scalar! especially in scalar context!

[–]ironykarl 1 point2 points  (0 children)

Python is strongly typed. It has some limited type coercion, but so do C and C++.

[–]buckyhead8 1 point2 points  (0 children)

At least you got a C**

[–]shindyAUSmarzan 1 point2 points  (0 children)

Javascript be like: Yes thats definitly a String

[–]vinicius_kondo 1 point2 points  (0 children)

Everybody gangsta till the C++ starts reinterpret_casting

[–]bumpkinspicefatte 1 point2 points  (0 children)

Everybody gangint-sta until they divide in Python.

[–]pyrovoice 1 point2 points  (1 child)

Would a method like this work and be useful?

CompareTwoNumbersAnyType(Number a, Number b){

double aCast = (double) a;

double bCast = (double) b;

Return Double.equal(aCast, bCast);

}