#include <stdio.h>
#include <stdlib.h>
/*
Calculate the volume of a cube in idiomatic C.
----------------------------------------------
A cube has equal side lengths. If each side has length "side",
the volume is:
volume = side * side * side
C does not have an exponent operator, and calling pow() for
integer exponents is slower and unnecessary. Multiplication
is the fastest and most idiomatic approach.
*/
/*
Compute the volume of a cube.
- side: length of one side (must be non-negative)
Returns: the cube's volume.
*/
double cube_volume(double side) {
if (side < 0.0) {
fprintf(stderr, "Error: side length must be non-negative.\n");
exit(EXIT_FAILURE);
}
// Fastest and idiomatic way to compute side³ in C
return side * side * side;
}
int main(void) {
double side = 8.0;
printf("Side length: %.2f\n", side);
printf("Volume of cube: %.2f\n", cube_volume(side));
return 0;
}
/*
run:
Side length: 8.00
Volume of cube: 512.00
*/