Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C

Multiplication assignment (`*=`) in C

Use `*=` to multiply the current value and store the result in the same object. The left operand is evaluated once, but you still need a bounds check before doubling a capacity.

Version: ISO C23; implementation support may vary

Syntax

lhs *= rhs

In C, multiplication assignment (*=) multiplies the current value of lhs by rhs and stores the result in the object designated by lhs. The left operand must be a modifiable lvalue of arithmetic type, and both types must be valid for *. The operator does not accept pointers, and C does not allow operator overloading. The rules here are for ISO C23; implementation support for C23 may vary.

Think of lhs *= rhs as lhs = lhs * (rhs), but do not blindly rewrite it: *= evaluates the left operand only once, so capacities[i++] *= 2 increments i once. That does not mean the left operand is evaluated before the right. The assignment expression has the stored value but is not an lvalue. For an atomic object, *= is an atomic read-modify-write with memory_order_seq_cst ordering.

The usual arithmetic conversions determine the type of the multiplication; the product is then converted to the destination type. Overflow in signed integer multiplication is undefined behavior; unsigned multiplication wraps modulo one more than the maximum of its result type. An unsigned destination does not guarantee unsigned multiplication: integer promotions can lead to int arithmetic.

Before doubling a size_t capacity, compute max_elements = SIZE_MAX / sizeof(element_type), where element_type is the element type and SIZE_MAX from <stdint.h> is the maximum size_t value. Reject a capacity greater than max_elements / 2 before using *= 2. This checks that both the new element count and its byte size are representable; it does not guarantee that allocation will succeed. *= itself does not allocate memory.

Examples

#include <stddef.h>
#include <stdint.h>
#include <stdio.h>

int main(void)
{
    size_t capacities[] = {4, 8};
    size_t i = 0;
    const size_t max_elements = SIZE_MAX / sizeof(unsigned char);

    if (capacities[i] > max_elements / 2) {
        return 1;
    }

    capacities[i++] *= 2;
    printf("capacities[0] = %zu, capacities[1] = %zu, i = %zu\n",
           capacities[0], capacities[1], i);
    return 0;
}

Result

capacities[0] = 8, capacities[1] = 8, i = 1

The example allocates no buffer and uses `sizeof(unsigned char)`, which is 1. The first capacity doubles from 4 to 8, the second stays at 8, and `i` goes from 0 to 1.

Related lessons

  • C · Lesson 74 · Advanced · Version: 3

Sources