Home > Net >  C Language - Non-explicit Conversion of Pointers
C Language - Non-explicit Conversion of Pointers

Time:01-05

For instance,

float get_at_index(ring_buffer_t *buffer, ring_buffer_size_t index) {
    if (index >= ring_buffer_num_items(buffer)) { /* No items at index */
        return 0;
    }
    
    /* Add index to pointer */
    ring_buffer_size_t data_index = ((buffer->tail_index   index) & RING_BUFFER_MASK);
    return buffer->buffer[data_index];
}

Does it make a difference to make the last line with (float) conversion?

CodePudding user response:

To summarize the code in your question:

float get_at_index(<parameters>) {
    <code>
    return buffer->buffer[data_index];
}

and you're asking whether it would make any difference if the last line were:

    return buffer->buffer[data_index];

The answer is no.

A return statement in a function returning float will, if possible, implicitly convert the expression to float. An explicit conversion (i.e., a cast) will perform exactly the same conversion.

It happens that the types that can be implicitly converted to float are the same as the types that can be explicitly converted to float, i.e., the arithmetic types. There are other conversions that can only be done with a cast, such as conversions from one pointer type to another, or a pointer to an integer, or an integer to a pointer.

One drawback of using a cast here is that if you later decide to change the return type of the function to, say, double, you'd still be explicitly converting the expression to float, and the result of that conversion would then be implicitly converted to double. Letting the compiler figure out the target type is often safer than specifying it yourself.

A quick Google search shows a possible definition of ring_buffer_t as a structure with a buffer member of type char*. If you're using that definition or one like it, you're converting a char value to float. That's rarely a sensible thing to do. It's likely that it would make more sense for your get_at_index function to return a char result rather than a float result. But it's impossible to be sure without seeing more of your code. (I'm not suggesting you post it here, because it's not directly relevant to your question.)

Also, the title of your question is "C Language - Non-explicit Convertion of Pointers". There are no pointer conversions in the code you showed us. (If buffer->buffer[data_index] were of pointer type, it would be illegal to convert it to float, either implicitly or explicitly.)

CodePudding user response:

I am assuming you intend to return a pointer to a float in your get_at_index function, and have made a typo in the function's definition. In that case, no, you would not need to explicitly cast the pointer into a float pointer.

  • Related