Questions tagged [conditional-operator]

The conditional operator is a ternary operator that is part of the syntax for a basic conditional expression in several programming languages. It is also commonly referred to as the ternary operator or inline if. Different languages have different syntax for the same construct, but all select between one of two options based on a condition.

6
votes
0answers
133 views

Function pointer indirection not optimized by gcc or clang - bug or intended?

Given the following two functions: int f() { return 0; } int g() { return 1; } And the following code to invoke one of them depending on a boolean b: int t0(bool b) { return (b ? &f : &g)();...
0
votes
2answers
39 views

Why can't I use return() in a conditional for flow control in Python?

Consider this function: def parity(num): num % 2 == 0 and return "that is even" return "that is odd" The first line of the function is a syntax error (I'm using v 3.7.3). Why? Seems like ...
3
votes
1answer
39 views

Conditional operator returns value from a copy of its argument

When the two return arguments to the conditional operator c?x:y are not of the same type, a copy is made before the cast is applied. Can this be prevented while still keeping simple useabiltiy? I ...
0
votes
0answers
27 views

Odd behaviour regarding conditional operator [duplicate]

Basically I have this piece of code: double booster = 1d; String result = booster % 1d == 0 ? ((int) booster) + "" : booster + ""; Where result returns either 1 or 1.X depending on input. This is ...
-1
votes
0answers
31 views

tslint gives 'no-unused-expression' warning

Tslint shows warning 'no-unused-expression' unused expression, expected an assignment or function call (no-unused-expression)tslint(1) Is it bad practice to use the shorthand-if statement as ...
12
votes
1answer
310 views

Why doesn't C++ allow implicit list initialization in the conditional operator? [duplicate]

This code compiles: std::string f(bool a, std::string const& b) { if (a) return b; return {}; } This code also compiles: std::string f(bool a, std::string const& b) { return a ? ...
4
votes
1answer
46 views

Taking the address of a conditional expression

I have the following code: struct S { int x; }; #define X(a, s) ((struct S*)(a ? &s : 0)) int main(void) { int a; struct S s; struct S *t; int *x; a = 3; s.x = 4; ...
1
vote
3answers
39 views

What is the shortest way to write condition variable in rails view template?

I have to put something in my .erb template , which uses conditional operator. In the code below you can see I am checking the conditional value and printing the same value if its not nil. <%= (@...
1
vote
1answer
33 views

Assigning values inside conditional operator

Is it good practice that assigning value to variables inside conditional operator ? This is about conditonal/turnery operator not about if statement a===1 ? (b=2) : (b=0) I am getting lint warning ...
0
votes
1answer
42 views

How does associativity of operator work during evaluation of expression?

I was learning precedence rule in C++. In which conditional operator is said to have Right to Left associativity. I interpret this as evaluation of expression start from right and proceed to left. ...
1
vote
2answers
39 views

Conditional operator not evaluating properly

Problem I'm trying to assign a value to a variable using a conditional operator based on the string value of another variable. Code const test = fnUserPlatform.platform === ('ps4' || 'xb1' || 'pc'...
-1
votes
0answers
25 views

What can I replace the ':' operator with and what exactly is it doing in this code snippet? [duplicate]

I am working on an assignment and I am not sure what the operator ':' does. I was also wondering what I can replace it with. Thanks in advance! public int getLargest() { int largestInt = ...
-7
votes
2answers
76 views

Single line If condition without else clause [duplicate]

How can we write a single line If condition without else in the operator? Example: If(count==0) { count=2; } How can we write above like below: count=count==0?2; As ternary operator requires ...
-4
votes
5answers
75 views

invalid syntax with ternary operator after import within a single line script [duplicate]

I'm running some python as a single-line script, but getting the following error >>> import ipaddress; (ipaddress.IPv4Address('1.1.1.1') in ipaddress.IPv4Network('1.1.1.1/32')) ? raise ...
0
votes
2answers
44 views

How to compose a variable name in one line, as part of struct call?

I have NO idea if what i'm trying to accomplish is doable at all. I'm pretty new to C. I have a struct that contains a pointer to another struct, that contains yet another pointer to another struct. ...
1
vote
1answer
46 views

DynamoDB with begins_with ConditionalExpression

Given the following code, I'd like to prevent duplicates where the Sort Key of a given table doesn't already have a Sort key that begins_with 'account_': db.put({ TableName: process.env....
3
votes
1answer
57 views

Can I use conditional operator to pass an input stream to a function?

There are some cases were I cannot use if-else but Only we can use conditional operator ? for example in member initialization list e.g: struct vector{ vector(int n) : sz_{n}, elem{ n ? new int[n]...
0
votes
0answers
29 views

LINQ- to get the correct data :

Need to retrieve movementData on the basis of Amount Type if AmountType.Reserve then MovementData should be retrieved on the basis of LatestReserveDate if AmountType.RecoveryReserve then ...
0
votes
0answers
37 views

Possible Java bug with conditional operator [duplicate]

below code fails with NullPointerException somehow and I am not sure why: import java.util.*; public class MyClass { public static void main(String args[]) { Long x = null; Long ...
0
votes
0answers
69 views

C# Is there “Ternary-style” Exception Handling?

I sometimes run into situations where, if a line of code throws an exception, I don't care what the exception is or why it was thrown; I just need to take a generic action and move on. For example: ...
0
votes
1answer
40 views

Logic not working - matching values with ages in a list

I am trying to match particular values (val_A) to ages I have in a list (val_B) in csv format. I am using the below Python code but it's never meeting the first two criteria. The last two elif and ...
39
votes
3answers
3k views

Why and when does the ternary operator return an lvalue?

For a long time I thought that the ternary operator always returns an rvalue. But to my surprise it doesn't. In the following code I don't see the difference between the return value of foo and the ...
0
votes
0answers
25 views

Different behavior about conditional operator when using jdk1.7 and jdk1.8 [duplicate]

When I use jdk1.7 to run these code below, both of test1() and test2() cause null pointer excetpion. But when I switch to jdk1.8, test1() prints null and test2() causes null pointer exception. ...
1
vote
1answer
53 views

typescript infer string literal from ternary conditional

This is a simplified example: function doSomething(animal: 'bird' | 'fish'){ } let flies=true; const animal = flies ? 'bird' : 'fish' doSomething(animal); Typescropt infers type 'bird' | ...
0
votes
1answer
47 views

Do Powershell conditional operators support search in arrays of object?

I need to check if array of objects contains particular object via -in and -contain operators, but no luck, for example: PS C:\> ($3_devices = Get-MobileDevice -ResultSize 3).guid Guid ...
0
votes
2answers
50 views

Trouble understanding javascript syntax: if (parameter == “someValue”) parameter = “”

I'm having trouble understanding this JS syntax: function myFunction(a) { if (a =="someValue") a = ""; } Is this some sort of shorthand? As in: if "a" is equal to "someValue", then set "a" to be ...
2
votes
1answer
35 views

What is the meaning of the conditional expression for checking DrawItemState equivalence in Windows Forms?

I was reading the DrawItemState documentation and I encountered the following snippet of code: if ((e.State & DrawItemState.Selected) == DrawItemState.Selected ) brush = SystemBrushes....
19
votes
4answers
1k views

What is happening in “? :”? I have no idea about the return type

I think ((1 ? (int)1 : (unsigned int)2) > -1) results in 1 (true), but actually it is 0 (false) in Visual Studio 2017. I think the value of (1 ? (int)1 : (unsigned int)2) should be (int)...
4
votes
5answers
108 views

Java set values after if else loop in one line

How do I achieve setting the value inside if else in one line? String amount = myJSON.optString("cValue") double cValue = (amount != null && !amount.isEmpty()) ? Double.parseDouble(amount) : ...
2
votes
2answers
54 views

How can I conditionally render search results with ReactiveBase

I'm trying to conditionally render my Results component from within ReactiveBase, but every time I try to use a ternary operator it breaks the rendering. If I remove the ternary, results display. I'm ...
-3
votes
2answers
56 views

Possible without String?

I can’t solve this task without a string (don’t know yet) : "My program asks the user if he wants to see a smiley. If he answers with 'Y' he gets a ":)", other input will be a ":(". Use a conditional ...
2
votes
2answers
74 views

Use printf for ternary operator arguments with mixed types

I have a tricky, but interesting question. Hang in there! Let's assume I write embedded code, and I am in a system where I have to store values in 16bit unsigned to be compatible with other systems. ...
-1
votes
2answers
54 views

How to not evaluate the third part of a ternary operator unless necessary

For my program, I need the functionality of the below line of code. If the condition evaluates to true, I need the expression if false to not be evaluated due to a System.IndexOutOfRangeException. Is ...
0
votes
0answers
24 views

Conditional values in GLPK

I have a cost formula that needs to activate a value given certain conditions. To be more specific, I need a variable w to take the values (0, 100, 150), whenever the sum of a variable x is (<=0 , ...
0
votes
1answer
56 views

Why is the ternary operator in the for…of statement not working?

I am not sure why the ternary operator is not working in this example. I have seen it used in similar ways before but I can not get it to work properly in this test. Any help would be greatly ...
12
votes
1answer
512 views

Conditional ? : operator with class constructor

could someone explain me why c and c1 are constructed different way. I understand that I have reference to copy created by '?' operator, which is destroyed after construction, but why in first case it ...
4
votes
1answer
139 views

Value category of conditional operator

Consider the following code: int x; int& f() { return x ? x : throw 0; } With gcc version 7.3.0 (Ubuntu 7.3.0-27ubuntu1~18.04) I get the following compilation error: cannot bind non-const ...
1
vote
3answers
31 views

Possible to build a string using shorthand conditionals like this?

I am trying to add some parameters to my URL based on dropdown selections, I want to keep the code as short and sweet as possible so I'm trying to build a string for the parameters that leaves out any ...
2
votes
2answers
39 views

advanced ffl: conditional expression then-expressions activation

Here is a snippet from https://github.com/anura-engine/anura/blob/55bc02244f0faba5e0831578a3c1c9a82e7bf569/src/formula_function.cpp#L923-L931: FUNCTION_DEF(if, 2, -1, "if(a,b,c)") const ...
0
votes
0answers
38 views

Motif Search - Bash

I am trying to use "if" condition inside a for loop to check if the given motif is present in the fasta file and if Yes to print the header of the file. When I executed this, for f in *.fasta ; do ...
0
votes
3answers
86 views

Why can't I cout an endl in a conditional operator? [duplicate]

I am trying to print a comma-separated list of numbers by using a for loop, but I don't want there to be a comma after the last number, instead, I want there to be an endl. I have this code: for (...
-1
votes
2answers
112 views

C# - Prettier way to compare one value against multiple values in a single line of code [duplicate]

I have this piece of code: if (filter != RECENT && filter != TODAY && filter != WEEK && filter != MONTH && filter != ALLTIME) { filter = RECENT; } ...
0
votes
2answers
61 views

def inside if/else ternary expression

Is there a way to convert this: if counts: def a(l): return a_with_counts(l) else: def a(l): return a_without_counts(l) into a ternary expression? I tried something like ...
3
votes
1answer
99 views

Is there ever a reason for “? 1 : 0” in Verilog?

Computer Organization and Design (5th edition) by Hennessy and Patterson includes this Verilog code in Figure B.5.15 (p. B-37): ALUOut <= A < B ? 1:0; Is there any reason not to write this ...
0
votes
1answer
100 views

PHP7 Null Coalescing or if/then shorthand — Evaluate rather than return

For a long time I have wanted to be able to do this without the slight extra cruft: $test ='test'; echo !empty($test2) ? 'something before ' . $test2 : ''; That will return an empty string, because ...
0
votes
1answer
212 views

React JS inline style not applying

render() { const styles = { maxHeight: 'auto' } return ( <div styleName="sticky-social-share" className={this.state.open ? 'open': null} > <ul styleName="sticky-social-...
0
votes
1answer
50 views

Pandas Data Frame conditional flow with multiple columns

I have a data frame as follow: fix = pd.DataFrame() fix ['Home'] =['A','B','C','D','E'] fix ['Away'] =['F','G','H','I','J'] fix ['GD = -2'] = [0.2,0.3,0.5,0.1,0.6] fix ['GD = -1'] = [0.25,0.1,0.55,0....
2
votes
4answers
51 views

How do I declare a variable in the output of a Javascript ternary operator?

I am trying to teach myself about Ternary Operators, and am stuck on a problem. To best explain what I am trying to do, below is pseudocode of what I want my code to look like: const regex = /\d+k\d+/...
2
votes
3answers
1k views

Conditional expression/ternary operator

I don't understand this syntax. Python program to demonstrate ternary operator a, b = 10, 20 Use tuple for selecting an item print( (b, a) [a < b] ) Use Dictionary for selecting an item ...
48
votes
2answers
3k views

Getting unwanted NullPointerException in ternary operator - Why? [duplicate]

While executing the following code, I am getting a NullPointerException at line: value = condition ? getDouble() : 1.0; In earlier lines when I use null instead of getDouble() everything works and ...

http://mssss.yulina-kosm.ru