Ternary Operators in C++ (Conditional Assignment)

  Рет қаралды 127,294

The Cherno

The Cherno

Күн бұрын

Пікірлер: 143
@LucidStew
@LucidStew 7 жыл бұрын
"This whole series is my opinion, really" and it just so happens your opinion is awesome.
@rudiger86
@rudiger86 2 жыл бұрын
Aw everything is awesome
@DeanMichaud
@DeanMichaud 7 жыл бұрын
As a Sr. C++ developer, I am enjoying your series - I mentor new developers, and I have been watching your vids as alternate ways of explaining concepts to newcomers to C++. You have a great way of explaining a topic in a digestible manner - keep it up TheCherno.
@vertigo6982
@vertigo6982 5 жыл бұрын
You work at a company that mentors new jr devopers? Sounds like the perfect first job. I think most are terrified of getting that first job and not knowing if they'll be able to produce what is expected.
@patrickg2416
@patrickg2416 4 жыл бұрын
Edit: Cherno discussed it later in the video but fwiw: I'm essentially a beginner, little bit of experience in python, but anyway: I'm assuming that ternary operators could be a source of MAJOR headaches for Sr. devs and software bugs in general because there's a lot of... density? On one hand you're saving that small amount of runtime, but even if it appears cleaner, to find a bug in the program you're sorting character by character rather than statement by statement. My observation is that in writing code this way: COMMENT everywhere. Otherwise, although I agree with this form in terms of efficiency and I too, think it looks cleaner, this seems like a PERFECT way to create piles and piles of little typo-bugs and misplaced logic. Thoughts?
@honguyenminh
@honguyenminh 3 жыл бұрын
The charno
@jonsnow8543
@jonsnow8543 4 жыл бұрын
A better way to write this kind of nested conditional at 4:50 is: s_speed = s_level > 10 ? 15 : s_level > 5 ? 10 : 5; An old school C trick that with proper indentation makes the nested ternary assignment very nice to read and more readable than if...else if...else
@axeljeanguyot5401
@axeljeanguyot5401 2 жыл бұрын
Cool tips
@TheSeanXe
@TheSeanXe 2 жыл бұрын
Came here to write this, saw you mentioned it. Despite Ygritte's belief, It appears that you know your stuff, Jon Snow!
@archimedeis
@archimedeis 2 жыл бұрын
That's cool
@TheSast
@TheSast Жыл бұрын
wouldn't this be even more readable? s_speed = s_level > 10 ? 15 : s_level > 5 ? 10 : 5;
@mnbcify
@mnbcify Жыл бұрын
Thanks Jon Snow
@AndrewEsh
@AndrewEsh 5 жыл бұрын
You missed my favorite use of the ternary operator: conditional argument passing. You can use the ternary in the list of arguments to a function or method call like this: SetSpeed(s_Level > 5 ? 10 : 5); So the ternary is not just a replacement for an if statement. It can be used in places an if statement can not.
@freddy7304
@freddy7304 4 жыл бұрын
damn, thats pretty cool , thanks for that.
@necrobynerton7384
@necrobynerton7384 4 жыл бұрын
I know this comment is kinda old but damn that is quite amazing
@mathematicusterra-4370
@mathematicusterra-4370 4 жыл бұрын
Isn't that basically some sort of assignment
@AndrewEsh
@AndrewEsh 4 жыл бұрын
@@mathematicusterra-4370 Yes, a conditional assignment.
@D3r3k2323
@D3r3k2323 4 жыл бұрын
I mean you could just do if (s_Level > 5) SetSpeed(10); else SetSpeed(5);
@MultiPwolf
@MultiPwolf 7 жыл бұрын
I think that the ternary operator when - even when nested - can lead to more readable code int a{ 30 }; int b{ 20 }; (a == b) ? cout b) ? cout
@lycanthoss
@lycanthoss 4 жыл бұрын
ternary should be used for one liners, not nested if/elses
@TheMR-777
@TheMR-777 4 жыл бұрын
@@lycanthoss That's also considered one liner, the man (@MultiPwolf) written. It's just a ... Syntactic Sugar, which is added in it. That's It. By the way, Nice Idea @MultiPwolf!
@akshatsamdani
@akshatsamdani Жыл бұрын
Isn't assignment are like int a =30?
@TheMastercheeff
@TheMastercheeff 6 жыл бұрын
Nesting ternary statements was not a concept I had considered before watching this, thanks.
@Buzz-pc4ep
@Buzz-pc4ep Жыл бұрын
# max value for 3 variable #include using namespace std; static int a = 10; static int b = 1000; static int c = 500; int main() { int value = a>b? a>c? a:c:b>c? b:c; //max value cout
@WillSams
@WillSams Жыл бұрын
For someone coming from C# and modern JavaScript, I appreciate your opinion on these videos. They have helped me a ton as I get back into C/C++. Thanks!
@OnoxOrion
@OnoxOrion 6 жыл бұрын
You are above s_Level 10 but we do not grant you the rank of "Master"
@redcrafterlppa303
@redcrafterlppa303 3 жыл бұрын
I like to put extra brackets around the boolean part like this : s_Speed = (s_Level > 5) ? 10 : 5; To clear up that this is like the condition block of an if statement. Looks much clearer in my opinion even though it is 2 extra symbols
@ultimatedragon4281
@ultimatedragon4281 2 жыл бұрын
I also think that makes more sense.
@mytech6779
@mytech6779 7 жыл бұрын
I just noticed the increase in the terminal font sizesince the early videos, very nice upgrade thank you.
@systematicloop3215
@systematicloop3215 7 жыл бұрын
You are seriously spoiling us with the daily videos.
@CaptainCyGr
@CaptainCyGr 4 жыл бұрын
Simple, understandable, without too much talking. Thanks
@h.hristov
@h.hristov 7 жыл бұрын
Thanks for this, didn't know you could nest it!
@motionsmoments6254
@motionsmoments6254 3 жыл бұрын
in each of the video of this tutorial series I learned something new even though I am an intermediate level at programming... kudos to you
@krec348
@krec348 7 жыл бұрын
Thanks once again TheCherno ;)
@neiltsakatsa
@neiltsakatsa 7 жыл бұрын
Thanks Cherno ! I'm really enjoying your series :-)
@glpinho
@glpinho 4 жыл бұрын
std::string next_action = understand_everything ? "Next video!" : "Leave a comment down below";
@ehrenmurdick
@ehrenmurdick 2 жыл бұрын
i like how your intro gets all smashed together, esp watching at 2x -- "hewsupguysmynimsaCherno and welcome back to my c++ series."
@websurfer5283
@websurfer5283 6 жыл бұрын
A nice video that i was able to digest much easier than some of the harder ones. Great series. Will be contributing to patreon 1st April to get whole months worth.
@Yupppi
@Yupppi Жыл бұрын
The question is "why wouldn't you write the ternary logical operator chain in parenthesis"? Like I'll never understand people who make exercise papers or notes or code or whatever that relies solely on being on point in complicate calculation order or everything goes wrong. When you could just use parenthesis whenever it might be slightly ambiguous and save everyone headache. Like as an engineer my design perspective is "whenever there's a chance of someone misusing it, remove the possibility of misusing it" or assemblying it wrong or whatever the case, the point is remove all possible cases of mistakes when they don't cost you anything to remove.
@ramansarabha871
@ramansarabha871 3 жыл бұрын
❤❤❤ this series. It's a gem.
@ParhamSalamati
@ParhamSalamati 9 ай бұрын
Wow! I didn't even know you could nest ternary operators! That was neat, and complicated for my future self that needs to read that at the same time! lol
@sing759
@sing759 5 жыл бұрын
i am getting halfway of your awesome tutorial
@KPkiller1671
@KPkiller1671 7 жыл бұрын
Damn, we are on a 4 day streak! Good job Cherno :) Really love your content
@cem_kaya
@cem_kaya 4 жыл бұрын
in school homeworks we are encouraged to nest the Ternary Operators cause we get to change 3 lines after homework grading to get a higher regrade.
@mint6276
@mint6276 3 жыл бұрын
To this day I still believe that this is the most bizarre C++ syntax to exist. Although, I am quite used to it because I see this in other languages as well. lol
@sujayshetty1618
@sujayshetty1618 5 жыл бұрын
Thanks for this great series. By the way, does your eye color change according to your dress color?
@MegtaBubble
@MegtaBubble 7 жыл бұрын
But I like nesting them, so much less code that can also be hard to overlook. You can also use new lines to make it more legible.
@sandspatel
@sandspatel 6 жыл бұрын
Was initially confused by the statement that ternary operator use vs. Conditional if statement use being "faster" because of the latter throwing away the variable. In researching I've found this is actually the variable being set an extra time not "thrown out". So in practice the overhead is likely v small anyway. Personally I'd only use ternary operators for simple one liner jobs and generally decide usage based on clarity and readability. Cheers.
@michalsebek2089
@michalsebek2089 6 жыл бұрын
I like this style: int var = (cond1 ? 1 : (cond2 ? (cond3 ? 2 : 3) : 4));
@freddy7304
@freddy7304 4 жыл бұрын
what does this mean ?
@michalsebek2089
@michalsebek2089 4 жыл бұрын
@@freddy7304 Isn't it obvious? It's short for: int var; if(cond1) { var = 1; } else if(cond2) { if(cond3) { var = 2; } else { var = 3; } } else { var = 4; }
@freddy7304
@freddy7304 4 жыл бұрын
@@michalsebek2089 so if cond 2, then var = 3?
@michalsebek2089
@michalsebek2089 4 жыл бұрын
@@freddy7304 if cond2, then it depends on cond3. If not cond1 and cond2 and cond3, then var = 2. If not cond1 and cond2 and not cond3, then var = 3.
@voynich7119
@voynich7119 2 жыл бұрын
Huh, I only ever knew that you could do this: s_Level > 5 ? s_Speed = 10 : s_Speed = 5; The way you did it was new for me: s_Speed = s_Level > 5 ? 10 : 5;
@ehsmou3411
@ehsmou3411 5 жыл бұрын
You are awesome man!
@sykn3z
@sykn3z 7 жыл бұрын
Thanks bro, keep it up with the videos and thank you for using your time to explain it just perfect!
@xeridea
@xeridea 3 жыл бұрын
If line starts getting long, from long variable names, strings or whatever, I will put the values on 2 new lines, so it is still shorthand, but still readable. I don't like to nest them though.
@fenjiehuang6475
@fenjiehuang6475 6 жыл бұрын
Thank you for your great video
@seal0118
@seal0118 4 жыл бұрын
cherno, you are a chad, you are the chadest of chads
@spiritwolf448
@spiritwolf448 7 жыл бұрын
Wow you're really *cherno* ing out a lot of videos lately!
@ididauni166
@ididauni166 3 жыл бұрын
6:40 We all need to talk about life. Ye, this smacks.
@ashwinikaswan9951
@ashwinikaswan9951 4 жыл бұрын
Great series on c++.
@Nick-lx4fo
@Nick-lx4fo 4 жыл бұрын
Thank you
@edwinov
@edwinov 6 ай бұрын
My favourite operator
@Игор-ь9щ
@Игор-ь9щ 7 жыл бұрын
the best series
@Hopsonn
@Hopsonn 7 жыл бұрын
agree
@szinton
@szinton 7 жыл бұрын
Oh hi Hopson =D Don't you know all of these things yet ? ;D
@Hopsonn
@Hopsonn 7 жыл бұрын
Nah I do, I am here to help people in the comments as I doubt Cherno has time to help everyone xD
@szinton
@szinton 7 жыл бұрын
Thats really nice =)
@chainonsmanquants1630
@chainonsmanquants1630 4 жыл бұрын
Thanks
@oncetherewasausernamesolon9234
@oncetherewasausernamesolon9234 3 жыл бұрын
Chernary operators lets go
@ali51717
@ali51717 4 жыл бұрын
Watching JASON Turner EP 125, explains a lot more stuff about why Ternary might be faster (or slower)
@dx2002sg
@dx2002sg 3 жыл бұрын
one of best c++ video. my question is how old are you? you from australia?
@appsenence9244
@appsenence9244 2 жыл бұрын
Amazing channel :D
@RogerTannous
@RogerTannous 4 жыл бұрын
1. Isn't it better if we enclose the expression in parentheses ? It will be clearer, especially if it's not the only statement on the same line. 2. you've named the members s_Level and s_Speed because they're static, right ? So why public (non-static) were prefixed with m_ instead of p_ for example ?
@RogerTannous
@RogerTannous 4 жыл бұрын
ooh, they're not class members, but the question still applies
@ralfneugebauer1216
@ralfneugebauer1216 2 жыл бұрын
Hello. In this video was said that the ternary operator can be faster than creating an empty string object and then performing an if-else-condition to assign a value. Doesn't the compiler optimize that away when creating the release? Bye.
@FSTiago
@FSTiago 7 жыл бұрын
In the s_Speed example, is there a gain in the performance in choosing the ternary operator instead of the if-else control? When no variable is created, does it uses the same number of internal operations or so?
@Hopsonn
@Hopsonn 7 жыл бұрын
The generated machine code should be exactly the same, it's really just a readability tool. A big use: It allows you to have a sort of "if statement into function argument", so you can decide what to pass into function arguments depending on a condition. Eg: void function (int x) { //blah blah } int main() { bool foo; //Code here which makes `foo` either true or false function(foo ? 10 : 20); //as opposed to: if (foo) { function(10); } else { function(20); } }
@FSTiago
@FSTiago 7 жыл бұрын
Hopson thanks! Nice example!
@Thesurvivour-yl3hd
@Thesurvivour-yl3hd 7 жыл бұрын
Hi Hopson! Makes sense.
@smileynetsmileynet7922
@smileynetsmileynet7922 4 жыл бұрын
Thats why I use () in my ternary operator.
@farsanrashid5601
@farsanrashid5601 6 жыл бұрын
Another great content though 3:32 is slightly misleading. We are not really destroying the string rather after constructing we are assigning new value. "This whole series is my opinion." LOL
@AdriansNetlis
@AdriansNetlis 6 жыл бұрын
But if a statement is assigning 2 values, let's say: if (something < 5) { x = 1; y = 2; } else { x = 2; y = 1} or x = something < 5 ? 1 : 2 y = something < 5 ? 2 : 1 Would there be any performance difference between those? I see the second version being slower as it repeats the same statement twice? Are compilers smart enough to solve this?
@DainYanuka
@DainYanuka 5 жыл бұрын
Not sure about compile time, but it definitely helps in code cleanliness though.
@itsbk6192
@itsbk6192 4 жыл бұрын
I believe you can achieve the same effect with one line instead something < 5 ? x = 1, y = 2 : (y = 1, x = 2);
@freddy7304
@freddy7304 4 жыл бұрын
@@itsbk6192 Yeah thats what i was thinking too, you can definitely condense the two statements above .
@dynpallomah
@dynpallomah 3 жыл бұрын
isnt it the same as "cond && tvalue || fvalue"?
@freddy7304
@freddy7304 4 жыл бұрын
awesome, i would love to know what else you can do with ternary operators.
@sequeld
@sequeld 7 жыл бұрын
Sup Charno?
@ElijahAklamanu
@ElijahAklamanu 8 ай бұрын
I'm confused why there is assigning of the variables before int main I thought it would be typically done after int main
@jamescullins2709
@jamescullins2709 5 жыл бұрын
well done, you answered a question I had, is it faster?
@jannesopanen8032
@jannesopanen8032 2 жыл бұрын
Hey! Do you a tutorial about different writing syntaxies ?
@BalkybekYera
@BalkybekYera 2 жыл бұрын
Why I am getting 1 in this case, but not 5?: s_level =9; s_speed=s_level>10 ? s_level>5 ? 10 : 5 : 1; //if (s_level>10) s_speed=10; else if(s_level>5) s_speed=5; else s_speed=1;
@KingdomTerrahearts
@KingdomTerrahearts 4 жыл бұрын
I am sorry The Cherno, for I have sinned, I used nested ternarys for a construct game because I do not actually like Construct in general.
@TechyHandle
@TechyHandle 4 жыл бұрын
Can we use block of code instead of just returning the value ?
@sumitkamble_
@sumitkamble_ Жыл бұрын
No more confusion with ternary operator again
@anashiarehman9557
@anashiarehman9557 6 жыл бұрын
TYSM.
@Xeab
@Xeab 4 жыл бұрын
I find wrapping the condition in parentheses helps with readability.
@Xeab
@Xeab 4 жыл бұрын
writing the nested one like: s_Speed = (s_Level > 5) ? ((s_Level > 10) ? 15 : 10) : 5;
@Mr.PM1993
@Mr.PM1993 Жыл бұрын
nah pass I go with my if clauses I technically have 16gb ram :D, if I had a micr controller in hand I would consider this
@snowjohn1639
@snowjohn1639 4 жыл бұрын
Can you add subtitle for other people? Thank you very much, your video will be better and professional!
@AbdulMoiz-ho8rx
@AbdulMoiz-ho8rx 2 жыл бұрын
Good
@danielesquivel3155
@danielesquivel3155 4 жыл бұрын
buena crack :3
@bloodwolf8307
@bloodwolf8307 4 жыл бұрын
cool
@ragsbigfella
@ragsbigfella 7 жыл бұрын
Hello Cherno, Can you please create some videos on C++ 11 and C++14 new features?
@nazar1744
@nazar1744 7 жыл бұрын
that would be useless because there is C++17 already
@TheCherno
@TheCherno 7 жыл бұрын
Actually no that wouldn't be useless, because C++11/14 introduces features that aren't new in C++17...
@TheCherno
@TheCherno 7 жыл бұрын
Yes, we'll get to those eventually. :)
@RogerTannous
@RogerTannous 4 жыл бұрын
@@TheCherno, can we invoke g++ in a way (with some arguments) so that we get the C++ version(s) that are currently supported ? Also, how do we tell g++ to compile for a specific target version of C++ ?
@RogerTannous
@RogerTannous 4 жыл бұрын
The answer to the second question is:: g++ -std=c++17 .... Found with:: g++ --help -std= Assume that the input sources are for .
@LuxeonIII
@LuxeonIII 6 жыл бұрын
Ternary operator has restrictions. First 2 lines work, second 2 do not, j++ and j-- do not change j It just happened to be the first thing I tried when learning about Ternary operators. j = 0; j = j == 0 ? j = 1 : j = -1; j = 0; j = j == 0 ? j++ : j--;
@freddy7304
@freddy7304 4 жыл бұрын
you dont include the variable name in the expression
@Николай-л3е4н
@Николай-л3е4н 2 жыл бұрын
This will work: j = (j == 0) ? ++j : --j;
@jhvhj6429
@jhvhj6429 2 жыл бұрын
It's not working because you are using post-increment (j++). It will work with pre-increment (++j) as shown below: j = (j == 0) ? ++j : --j; Post-increment will evaluate to j = j++; Pre-increment will evaluate to j = ++j; OR even better, be explicit about the incrementation: j = (j == 0) ? (j + 1) : (j - 1);
@lucustaylor4585
@lucustaylor4585 5 жыл бұрын
I am not paypal I have alipay. I want support you.
@sametsahin-eh3qj
@sametsahin-eh3qj Жыл бұрын
cant tell if he is russian or irish
@minecraftcookie2929
@minecraftcookie2929 Жыл бұрын
nah i aint doin that
@abderezakabidi4510
@abderezakabidi4510 4 жыл бұрын
Good series, but just some time you passed so fast when you explain some informations, otherwise excellent series keep uploading videos
@AgentM124
@AgentM124 7 жыл бұрын
mind = blown > 1 ? blown > 2 ? blown > 3 ? "yes" : "maybe" : "no";
@juubes5557
@juubes5557 7 жыл бұрын
blown == 5 true
@vitorkiguchi4670
@vitorkiguchi4670 7 жыл бұрын
I think you need another value there, so it would be mind = blown > 1 ? blown > 2 ? blown > 3 ? "totally" : "yes" : "maybe" : "no"; So 4 or greater would give you "totally", 3 would give you "yes", 2 would give you "maybe" and 1 or less would give you "no";
@websurfer5283
@websurfer5283 6 жыл бұрын
LOLol
@dvirarazi7351
@dvirarazi7351 6 жыл бұрын
I'd write it a bit differently, just for organization sake: mind = blown < 1 ? "no" : blown < 2 ? "maybe" : blown < 3 ? "yes" : "totally";
@GenericPhantom1
@GenericPhantom1 Жыл бұрын
This is just an if statement but it's compressed into less code
@pizzaguy_
@pizzaguy_ Жыл бұрын
A tiny bit more optimized, from what I've learned.
@forhadrh
@forhadrh 3 жыл бұрын
6:42 - but some wise said: programmer has no life...
@RiverBeard
@RiverBeard 3 жыл бұрын
rank = is Cherno ? Master : pleb;
@timovaringjarson
@timovaringjarson 7 жыл бұрын
Compiler dependent at least the GNU Compiler series(also NVIDIA shaders) compile it down to assembler cmov (conditional forward), but becourse too many people misunderstood the difference it become a thing of disput, same goes for std::endl which flashes the buffer and is not same thing as , and again many people use std::endl, where their is absolutely no need, so should it be also removed from the spec or compile it down so something more 99% programmer friendly. Sorry for my bad english. #saveternaryoperator
@coreyyotto
@coreyyotto 7 жыл бұрын
Great video as always, but the that echo on the microphone is getting kind of annoying.
@leelomchen3119
@leelomchen3119 6 жыл бұрын
are you ok?i'm fine thank you and you:boring
@nazar1744
@nazar1744 7 жыл бұрын
2/10 "We don't like the dark background of VS" -IGN
@09087132
@09087132 7 жыл бұрын
FIRST
@serkanozturk4217
@serkanozturk4217 2 жыл бұрын
Personal Notes: - canBuyMercedesA180 = money > 60k $ ? true: false
How to CREATE/INSTANTIATE OBJECTS in C++
13:03
The Cherno
Рет қаралды 245 М.
CONST in C++
12:54
The Cherno
Рет қаралды 411 М.
How many people are in the changing room? #devil #lilith #funny #shorts
00:39
I thought one thing and the truth is something else 😂
00:34
عائلة ابو رعد Abo Raad family
Рет қаралды 8 МЛН
Can You Find Hulk's True Love? Real vs Fake Girlfriend Challenge | Roblox 3D
00:24
C ternary operator ❓
2:53
Bro Code
Рет қаралды 33 М.
Writing an ITERATOR in C++
19:44
The Cherno
Рет қаралды 126 М.
Harder Than It Seems? 5 Minute Timer in C++
20:10
The Cherno
Рет қаралды 217 М.
Type Punning in C++
13:20
The Cherno
Рет қаралды 159 М.
C++ Ternary Operator (Conditional Operator) | CPP Video Tutorial
4:44
I did a C++ University Assignment
50:23
The Cherno
Рет қаралды 299 М.
Copying and Copy Constructors in C++
20:52
The Cherno
Рет қаралды 437 М.
Macros in C++
19:36
The Cherno
Рет қаралды 242 М.
why are switch statements so HECKIN fast?
11:03
Low Level
Рет қаралды 428 М.
WHY did this C++ code FAIL?
38:10
The Cherno
Рет қаралды 294 М.
How many people are in the changing room? #devil #lilith #funny #shorts
00:39