Тёмный

Ternary Operators in C++ (Conditional Assignment) 

The Cherno
Подписаться 645 тыс.
Просмотров 121 тыс.
50% 1

Patreon ► / thecherno
Twitter ► / thecherno
Instagram ► / thecherno
Slack ► slack.thecherno.com
Discord ► / discord
Series Playlist ► • C++
Gear I use:
-----------------
BEST laptop for programming! ► geni.us/pakTES
My FAVOURITE keyboard for programming! ► geni.us/zNhB
FAVOURITE monitors for programming! ► geni.us/Ig6KBq
MAIN Camera ► geni.us/t6xyDRO
MAIN Lens ► geni.us/xGoDWT
Second Camera ► geni.us/CYUQ
Microphone ► geni.us/wqO6g7K

Опубликовано:

 

29 авг 2017

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 145   
@LucidStew
@LucidStew 6 лет назад
"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 6 лет назад
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 3 года назад
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 2 года назад
The charno
@jonsnow8543
@jonsnow8543 3 года назад
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 4 года назад
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 3 года назад
I know this comment is kinda old but damn that is quite amazing
@mathematicusterra-4370
@mathematicusterra-4370 3 года назад
Isn't that basically some sort of assignment
@AndrewEsh
@AndrewEsh 3 года назад
@@mathematicusterra-4370 Yes, a conditional assignment.
@D3r3k2323
@D3r3k2323 3 года назад
I mean you could just do if (s_Level > 5) SetSpeed(10); else SetSpeed(5);
@TheMastercheeff
@TheMastercheeff 6 лет назад
Nesting ternary statements was not a concept I had considered before watching this, thanks.
@MultiPwolf
@MultiPwolf 6 лет назад
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 11 месяцев назад
Isn't assignment are like int a =30?
@mytech6779
@mytech6779 6 лет назад
I just noticed the increase in the terminal font sizesince the early videos, very nice upgrade thank you.
@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!
@neiltsakatsa
@neiltsakatsa 6 лет назад
Thanks Cherno ! I'm really enjoying your series :-)
@ehrenmurdick
@ehrenmurdick 2 года назад
i like how your intro gets all smashed together, esp watching at 2x -- "hewsupguysmynimsaCherno and welcome back to my c++ series."
@systematicloop3215
@systematicloop3215 6 лет назад
You are seriously spoiling us with the daily videos.
@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.
@h.hristov
@h.hristov 6 лет назад
Thanks for this, didn't know you could nest it!
@redcrafterlppa303
@redcrafterlppa303 2 года назад
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.
@krec348
@krec348 6 лет назад
Thanks once again TheCherno ;)
@KPkiller1671
@KPkiller1671 6 лет назад
Damn, we are on a 4 day streak! Good job Cherno :) Really love your content
@CaptainGeorge3
@CaptainGeorge3 3 года назад
Simple, understandable, without too much talking. Thanks
@OnoxOrion
@OnoxOrion 6 лет назад
You are above s_Level 10 but we do not grant you the rank of "Master"
@sykn3z
@sykn3z 6 лет назад
Thanks bro, keep it up with the videos and thank you for using your time to explain it just perfect!
@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
@ParhamSalamati
@ParhamSalamati 4 месяца назад
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
@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
@ramansarabha871
@ramansarabha871 2 года назад
❤❤❤ this series. It's a gem.
@ehsmou3411
@ehsmou3411 4 года назад
You are awesome man!
@fenjiehuang6475
@fenjiehuang6475 6 лет назад
Thank you for your great video
@sujayshetty1618
@sujayshetty1618 5 лет назад
Thanks for this great series. By the way, does your eye color change according to your dress color?
@oncetherewasausernamesolon9234
@oncetherewasausernamesolon9234 3 года назад
Chernary operators lets go
@appsenence9244
@appsenence9244 2 года назад
Amazing channel :D
@spiritwolf448
@spiritwolf448 6 лет назад
Wow you're really *cherno* ing out a lot of videos lately!
@Nick-lx4fo
@Nick-lx4fo 3 года назад
Thank you
@ashwinikaswan9951
@ashwinikaswan9951 3 года назад
Great series on c++.
@chainonsmanquants1630
@chainonsmanquants1630 3 года назад
Thanks
@freddy7304
@freddy7304 4 года назад
awesome, i would love to know what else you can do with ternary operators.
@sing759
@sing759 4 года назад
i am getting halfway of your awesome tutorial
@seal0118
@seal0118 3 года назад
cherno, you are a chad, you are the chadest of chads
@edwinov
@edwinov Месяц назад
My favourite operator
@ididauni166
@ididauni166 3 года назад
6:40 We all need to talk about life. Ye, this smacks.
@jamescullins2709
@jamescullins2709 5 лет назад
well done, you answered a question I had, is it faster?
@cem_kaya
@cem_kaya 3 года назад
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.
@MegtaBubble
@MegtaBubble 6 лет назад
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.
@danielesquivel3155
@danielesquivel3155 4 года назад
buena crack :3
@anashiarehman9557
@anashiarehman9557 5 лет назад
TYSM.
@dx2002sg
@dx2002sg 3 года назад
one of best c++ video. my question is how old are you? you from australia?
@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
@jannesopanen8032
@jannesopanen8032 2 года назад
Hey! Do you a tutorial about different writing syntaxies ?
@user-eh7hy2xn3w
@user-eh7hy2xn3w 6 лет назад
the best series
@Hopsonn
@Hopsonn 6 лет назад
agree
@szinton
@szinton 6 лет назад
Oh hi Hopson =D Don't you know all of these things yet ? ;D
@Hopsonn
@Hopsonn 6 лет назад
Nah I do, I am here to help people in the comments as I doubt Cherno has time to help everyone xD
@szinton
@szinton 6 лет назад
Thats really nice =)
@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.
@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;
@xeridea
@xeridea 2 года назад
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.
@sumitkamble_
@sumitkamble_ Год назад
No more confusion with ternary operator again
@FSTiago
@FSTiago 6 лет назад
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 6 лет назад
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 6 лет назад
Hopson thanks! Nice example!
@Thesurvivour-yl3hd
@Thesurvivour-yl3hd 6 лет назад
Hi Hopson! Makes sense.
@AbdulMoiz-ho8rx
@AbdulMoiz-ho8rx 2 года назад
Good
@user-sd4rj4sp1v
@user-sd4rj4sp1v 3 месяца назад
I'm confused why there is assigning of the variables before int main I thought it would be typically done after int main
@TechyHandle
@TechyHandle 4 года назад
Can we use block of code instead of just returning the value ?
@dynpallomah5918
@dynpallomah5918 2 года назад
isnt it the same as "cond && tvalue || fvalue"?
@bloodwolf8307
@bloodwolf8307 4 года назад
cool
@Yupppi
@Yupppi 7 месяцев назад
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.
@AdriansNetlis
@AdriansNetlis 5 лет назад
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 .
@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.
@sequeld
@sequeld 6 лет назад
Sup Charno?
@ali51717
@ali51717 3 года назад
Watching JASON Turner EP 125, explains a lot more stuff about why Ternary might be faster (or slower)
@RogerTannous
@RogerTannous 3 года назад
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 3 года назад
ooh, they're not class members, but the question still applies
@smileynetsmileynet7922
@smileynetsmileynet7922 3 года назад
Thats why I use () in my ternary operator.
@ragsbigfella
@ragsbigfella 6 лет назад
Hello Cherno, Can you please create some videos on C++ 11 and C++14 new features?
@nazar1744
@nazar1744 6 лет назад
that would be useless because there is C++17 already
@TheCherno
@TheCherno 6 лет назад
Actually no that wouldn't be useless, because C++11/14 introduces features that aren't new in C++17...
@TheCherno
@TheCherno 6 лет назад
Yes, we'll get to those eventually. :)
@RogerTannous
@RogerTannous 3 года назад
@@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 3 года назад
The answer to the second question is:: g++ -std=c++17 .... Found with:: g++ --help -std= Assume that the input sources are for .
@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;
@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.
@mba2ceo
@mba2ceo Год назад
what is faster ?
@Xeab
@Xeab 3 года назад
I find wrapping the condition in parentheses helps with readability.
@Xeab
@Xeab 3 года назад
writing the nested one like: s_Speed = (s_Level > 5) ? ((s_Level > 10) ? 15 : 10) : 5;
@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
@KingdomTerrahearts
@KingdomTerrahearts 3 года назад
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.
@glpinho
@glpinho 4 года назад
std::string next_action = understand_everything ? "Next video!" : "Leave a comment down below";
@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 3 года назад
Can you add subtitle for other people? Thank you very much, your video will be better and professional!
@LuxeonIII
@LuxeonIII 5 лет назад
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
@user-zz8rc2jy5y
@user-zz8rc2jy5y 2 года назад
This will work: j = (j == 0) ? ++j : --j;
@jhvhj6429
@jhvhj6429 Год назад
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);
@minecraftcookie2929
@minecraftcookie2929 8 месяцев назад
nah i aint doin that
@AgentM124
@AgentM124 6 лет назад
mind = blown > 1 ? blown > 2 ? blown > 3 ? "yes" : "maybe" : "no";
@juubes5557
@juubes5557 6 лет назад
blown == 5 true
@vitorkiguchi4670
@vitorkiguchi4670 6 лет назад
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";
@abderezakabidi4510
@abderezakabidi4510 3 года назад
Good series, but just some time you passed so fast when you explain some informations, otherwise excellent series keep uploading videos
@sametsahin-eh3qj
@sametsahin-eh3qj 7 месяцев назад
cant tell if he is russian or irish
@lucustaylor4585
@lucustaylor4585 4 года назад
I am not paypal I have alipay. I want support you.
@phantomstriker7996
@phantomstriker7996 Год назад
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.
@timovaringjarson
@timovaringjarson 6 лет назад
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
@RiverBeard
@RiverBeard 3 года назад
rank = is Cherno ? Master : pleb;
@Disillusioned_one
@Disillusioned_one 4 года назад
In my opinion, if you can not take your professional opinion who works for a large gaming company. Who can we take, I know who my choice is, in my opinion.
@forhadrh
@forhadrh 2 года назад
6:42 - but some wise said: programmer has no life...
@itsachickenwiththing
@itsachickenwiththing 6 лет назад
Great video as always, but the that echo on the microphone is getting kind of annoying.
@nazar1744
@nazar1744 6 лет назад
2/10 "We don't like the dark background of VS" -IGN
@leelomchen3119
@leelomchen3119 6 лет назад
are you ok?i'm fine thank you and you:boring
@09087132
@09087132 6 лет назад
FIRST
@serkanozturk4217
@serkanozturk4217 Год назад
Personal Notes: - canBuyMercedesA180 = money > 60k $ ? true: false
Далее
How to CREATE/INSTANTIATE OBJECTS in C++
13:03
Просмотров 237 тыс.
Stack vs Heap Memory in C++
19:31
Просмотров 554 тыс.
1❤️
00:17
Просмотров 5 млн
POINTERS in C++
16:59
Просмотров 1 млн
Ternary Operator | C++ Tutorial
4:22
Просмотров 1,6 тыс.
why do void* pointers even exist?
8:17
Просмотров 331 тыс.
ENUMS in C++
7:45
Просмотров 381 тыс.
how Google writes gorgeous C++
7:40
Просмотров 802 тыс.
How C++ Works
20:21
Просмотров 1 млн
BINARY vs TEXT File Serialization
13:49
Просмотров 47 тыс.
I Rewrote This Entire Main File // Code Review
16:08
Просмотров 131 тыс.