O.3.4 — Sizeof, comma, and conditional operators

Sizeof operator

Operator Symbol Form Operation
Sizeof sizeof sizeof(type)
sizeof(variable)
Returns size of type or variable in bytes

We covered the sizeof(type) form of the operator in lesson 2.3 -- Variable sizes and the sizeof operator. Refer to that lesson for more information on the sizeof(type) form of the operator.

Note that sizeof can also be used on a variable, and will return the size of that variable:

Comma operator

Operator Symbol Form Operation
Comma , x, y Evaluate x then y, returns value of y

The comma operator allows you to evaluate multiple expressions wherever a single expression is allowed. The comma operator evaluates to its rightmost operand.

For example:

z would be assigned the result of evaluating ++y, which equals 3.

In almost every case, a statement written using a comma would be better written as separate statements. For example, the above code should be written as:

Note that comma has the lowest precedence of all the operators, even lower than assignment. Because of this, the following two lines of code do different things:

Most programmers do not use the comma operator at all, with the single exception of inside for loops, where its use is fairly common. We discuss for loops in a future lesson.

Note that although a comma is used to separate the parameters in a function call, this is not using the comma operator.

Similarly, when declaring multiple variables on a single line, the comma there is just a normal separator, not the comma operator

Rule: Avoid using the comma operator, except within for loops.

Conditional operator

Operator Symbol Form Operation
Conditional ?: c ? x : y If c is nonzero (true) then evaluate x, otherwise evaluate y

The conditional operator (?:) (also known as the “arithmetic if” operator) is C++’s only ternary operator (it takes 3 operands). Because of this, it’s also sometimes referred to as the “ternary operator” (we suggest you avoid calling it this in case C++ adds another ternary operator in the future).

The ?: operator provides a shorthand method for doing a particular type of if/else statement.

If/else statements in the following form:

```if (condition)
expression;
else
other_expression;
```

can be rewritten as:

```(condition) ? expression : other_expression;
```

Note that the operands of the conditional operator must be expressions themselves (not statements).

For example, an if/else statement that looks like this:

```if (condition)
x = some_value;
else
x = some_other_value;
```

can be rewritten as:

```x = (condition) ? some_value : some_other_value;
```

Many people find this more compact form easier to read.

As another example, to put the larger of values x and y in variable larger, we could write this:

Or this:

It is common to put the conditional part of the expression inside of parenthesis, both to make it easier to read, and also to make sure the precedence is correct.

It is also worth noting that the expression between the ? and : is evaluated as if it were parenthesized.

Keep in mind that the ?: operator has a very low precedence. If doing anything other than assigning the result to a variable, the ?: statement needs to be wrapped in parenthesis.

For example to print the larger of values x and y to the screen, we could do this:

Or we could do this:

Because the << operator has higher precedence than the ?: operator, the statement:

would evaluate as:

That would print 1 (true) if x > y, or 0 (false) otherwise!

The conditional operator gives us a convenient way to simplify simple if/else statements, particularly when assigning the result to a variable or returning the result as part of a function return. It should not be used for complex if/else statements, as it quickly becomes both unreadable and error prone.

Rule: Only use the conditional operator for simple conditionals where it enhances readability.

The conditional operator evaluates as an expression

It’s worth noting that the conditional operator evaluates as an expression, whereas if/else evaluates as a set of statements. This means the conditional operator can be used in some places where if/else can not.

For example, when initializing a const variable:

There’s no satisfactory if/else statement for this. You might think to try something like this:

However, this won’t compile, and you’ll get an error message that classSize isn’t defined. Much like how variables defined inside functions die at the end of the function, variables defined inside an if or else statement die at the end of the if or else statement. Thus, classSize has already been destroyed by the time we try to print it.

If you want to use an if/else, you’d have to do something like this:

This one works because we’re not defining variables inside the if or else, we’re just returning a value back to the caller, which can then be used as the initializer.

That’s a lot of extra work!

The type of the expressions must match or be convertible

To properly comply with C++’s type checking, both expressions in a conditional statement must either match, or the second expression must be convertible to the type of the first expression.

So while you might expect to be able to do something like this:

The above example won’t compile. One of the expressions is an integer, and the other is a string literal. The compiler will try to find a way to convert the string literal to an integer, but since it doesn’t know how, it will give an error. In such cases, you’ll have to use an if/else.

87 comments to O.3.4 — Sizeof, comma, and conditional operators

• Randle

I remember learning the conditional operator in uni, but was never shown a proper example where it was necessary, so I ignored it. Thank you for providing a clear example of its usage!

• Brandon

How could I use the conditional operator in place of an if/else with multiple statements? I'm practicing by converting if/else statements to use the conditional operator but what about those with multiple else if's like a switch statement? Is that possible? or would it be bad practice since the point is to reduce the clutter of code? Thanks.

EDIT: I just noticed " It’s worth noting that the conditional operator evaluates as an expression, whereas if/else evaluates as a set of statements."

But still, can I only evaluate a single expression at once right?  Sorry if this sounds weird.

• nascardriver

Hi Brandon!

The conditional operator should only be used when you need the result of the expression.

You could use the comma operator to get what you want

But don't do it, it's ugly, use if-statements.

• Jules

So i wrote a simple assembly program to find the square of a number (2 in this case, haven't given the functionality of user input):
#include "pch.h"
#include <iostream>
int power(int);
int main()
{
std::cout << "Hello World!\n";
std::cout<<power(2);
}

int power(int x)
{
_asm
{
mov eax,x
imul eax,x
mov x,eax

}
return x;

}

my question is :
in the instruction mov x,eax does the compiler already know that the contents of eax should be moved into the MEMORY LOCATION of "x"
because the contents of the eax register cannot be moved into a variable.

consequently mov [x],eax works as well.
just wanted to know if the c++ compiler is optimized in handling asm in a way that traditional assemblers like NASM or FASM aren't.

• Jeremy

I can understand the logic of variables inside of functions being destroyed after the function call is over, but is there a specific reason why if/else statements share the same scope?

• Alex

The C++ specification says that if the if-statement or else-statement are not written as compound statements, they should be treated as if they were. So:

Is treated as if it were written:

And although we haven't covered blocks/compound statements yet (that happens in chapter 4), they behave similarly to functions in that local variables defined inside a block die at the end of the block.

• aleksandr.a

So you can use the conditional operator?
Thank.

• Rai

I tried using the conditional operator with one of the older lesson project.

How would you use conditional operators for the if statement here? I tried doing it with this :

But I was getting an error saying "error C4716: 'getInteger': must return a value"

• nascardriver

Without the full @getInterger function I can't tell you what your problem is.
Here's how you could do it

• leonidus007

Maybe this can help..

#include <iostream>
int getInteger()
{
std::cout << "Enter a single digit integer: " << std::endl;
int input;
std::cin >> input;
return input > 0 ? (input < 10 ? input : -1) : -1;
}
int main()
{
int y{ getInteger() };
std::cout << y;
return 0;
}