Because you are not familiar with the basics, you use the wrong terms. The phrase "Expressions within a variable" does not make sense. What exists is to assign an expression to a variable. Any high-level programming language can do this, it's basic.
Conditional expression
What you are really wondering is whether it is possible to have conditional expressions to generate the value to be assigned to the variable. And yes, this is possible. I do not know any language that can not do this. From the simplest expression to what it looks like you want to do.
Many programmers do not understand the operation of some language commands because they do not understand the basics. When you try to learn a lot in practice without understanding the theory, you will learn everything in half and it will always be harder to understand the whole. Commands such as if
, while
, and for
expect a Boolean value ( true
or false
) always to make a decision. This value can be obtained directly through the literal or through a conditional expression, which is more common. Examples:
while (true)
This value is as valid as while (variavel > 10)
. Well, then we can do this:
bool condicao = variavel > 10;
while (condicao)
What strikes me is that it is common for people to create excessive variables in programs. And in this case where a variable can be created with the conditional expression and then use the conditional command "nobody" thinks it's possible to do. I am not saying that this form should be used frequently, but at some point it may be useful. The important thing here is to understand what a conditional expression is.
There's no sense in doing:
bool condicao = variavel > 10;
while (condicao == true)
And I see people often do this. They think that in a if
or while
if it does not have a relational operator it is wrong. And it is just the opposite. It must have a Boolean value. Whether it is generated by an expression or a simple value does not matter. Another example:
if (arquivo.eof() == false)
It does not make sense, it would be better to do:
if(!arquivo.eof())
Ternary operator
But what you really want to know is whether you can create an expression where you test a condition and decide whether to use one of the following two results. Each language has a strategy to do this. C ++ uses a conditional ternary operator (because it has three operands).
It would look like this:
#include <iostream>
int main() {
int a = 1 > 2 ? 5 : 10;
std::cout << a;
return 0;
}
See working on ideone .
Questions that tell about this operator: