phreaknik
phreaknik

Reputation: 685

Is it acceptable to type-cast the return value of a C function?

A colleague of mine claims that type-casting the return value of a function is undefined in C, however I cannot find anything to support his claim.

I know that type-casting a function pointer is bad, see here: Casting a function pointer to another type

But I want to confirm that the following code would be acceptable and well defined:

// Some function
int ret = foo(bar);

// Some variable with some different type
unsigned int a;

// Cast function result to match variable type
a = (unsigned int) foo(bar);

Upvotes: 4

Views: 5739

Answers (1)

yLaguardia
yLaguardia

Reputation: 595

Other than what's answered in the comments, you can back your argument with some article like this, that repeatedly talks about casting return values.

One trivial example that we use every now and then is to cast the return value of the round() function.

This is so trivial that you can even see it mentioned in the C Standard, page 567 of this pdf.

In the above conversions from floating to integer, the use of (cast)x can be replaced with (cast)round(x), (cast)rint(x), (cast)nearbyint(x), (cast)trunc(x), (cast)ceil(x), or (cast)floor(x)

Upvotes: 2

Related Questions