←back to thread

2024 points randlet | 1 comments | | HN request time: 0.216s | source
Show context
js2 ◴[] No.17516019[source]
Background ("PEP 572 and decision-making in Python"):

https://lwn.net/Articles/757713/

replies(2): >>17516132 #>>17516693 #
jcelerier ◴[] No.17516132[source]
> The problem with the C-style of assignments is that it leads to this classic error: if(x = 0) {...}

yeah, if you code on 20 years old compilers with no warnings. GCC 4.1 warns about this (with -Wall) and Clang 3.4 warns about this too, without any warning flag.

replies(4): >>17516174 #>>17516220 #>>17517715 #>>17518178 #
iainmerrick ◴[] No.17517715[source]
What do you do if you really do intend the assignment?

(Assume for the sake of argument it’s some more reasonable example like "if (x = re_match(foo, bar)) {...}")

replies(3): >>17517838 #>>17517895 #>>17518252 #
1. thestoicattack ◴[] No.17518252[source]
C++17 has if-statement initializers, so you can do

    if (auto x = re_match(foo, bar); x.has_value()) {
(or x.ok() or whatever the name is of the method that tells you the validity of x)