Question

I've never seen a programming language with conditional assignment targets, eg.:

// If (x == y), then var1 will be set to 1, else var2 will be set to 1
((x == y) ? var1 : var2) = 1

The target of the assignment is determined conditionally at run-time, in this case based on whether x == y.

It seems like it could be a handy syntax.

Anyone know of any programming language which supports this?

Or is there a theoretical reason it can't be done effectively?

Était-ce utile?

La solution

This isn't really a theory question, but a practical one.

C++ supports what you're asking about:

[C++14: 5.16/4]: If the second and third operands are glvalues of the same value category and have the same type, the result is of that type and value category [..]

For example:

#include <iostream>

int x = 3, y = 4;

void foo(const bool b)
{
    (b ? x : y) = 6;
}

int main()
{
    std::cout << x << ' ' << y << '\n';   // 3 4
    foo(true);
    std::cout << x << ' ' << y << '\n';   // 6 4
    foo(false);
    std::cout << x << ' ' << y << '\n';   // 6 6
}

(live demo)

(This is basically the same as *ptr = val, since dereferencing produces an lvalue.)

It's worth noting that C doesn't support it:

#include <stdio.h>
#include <stdbool.h>

int x = 3, y = 4;

void foo(const bool b)
{
    (b ? x : y) = 6;
}

int main()
{
    printf("%d %d\n", x, y);   // 3 4
    foo(true);
    printf("%d %d\n", x, y);   // 6 4
    foo(false);
    printf("%d %d\n", x, y);   // 6 6
}

// main.c: In function 'foo':
// main.c:8:17: error: lvalue required as left operand of assignment
//      (b ? x : y) = 6;
             ^

(live demo)

… though it will allow you to simulate this technique, by applying my early observation regarding pointer dereferences:

*(b ? &x : &y) = 6;

Autres conseils

You can do this in Perl. It is the same as in C++.

my $x = 0;
my $y = 0;

1==1 ? $x: $y = 1;

print "x: $x y: $y\n";

$x = 0;
$y = 0;

1==0 ? $x: $y = 1;

print "x: $x y: $y\n";

Note: this construct can often lead to confusion. For example, consider the following code:

$condition ? $y = 0 : $x = 1;

The person writing this line of code likely thought that $y would get set to 0 if $condition is true, but actually this evaluates to $y = 0 = 1, which gives $y a value of 1.

Licencié sous: CC-BY-SA avec attribution
scroll top