Type-checked units in C
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
--- units.asm 2023-06-18 12:02:32.313569952 +1200 | |
+++ units_unsafe.asm 2023-06-18 12:02:32.313569952 +1200 | |
@@ -1,7 +1,7 @@ | |
-metres_from_feet(feet): | |
+metres_from_feet(double): | |
divsd xmm0, QWORD PTR .LC0[rip] | |
ret | |
-feet_from_metres(metres): | |
+feet_from_metres(double): | |
mulsd xmm0, QWORD PTR .LC0[rip] | |
ret | |
.LC3: |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
typedef struct { | |
double m; | |
} metres; | |
typedef struct { | |
double ft; | |
} feet; | |
metres | |
metres_from_feet(feet x) | |
{ | |
const feet m_to_ft = {3.28084}; | |
return (metres){x.ft / m_to_ft.ft}; | |
} | |
feet | |
feet_from_metres(metres x) | |
{ | |
const feet m_to_ft = {3.28084}; | |
return (feet){x.m * m_to_ft.ft}; | |
} | |
int | |
main(void) | |
{ | |
metres h = {2.4}; | |
printf("%lf metres = %lf feet\n", h.m, feet_from_metres(h).ft); | |
return 0; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
double | |
metres_from_feet(double x) | |
{ | |
const double m_to_ft = 3.28084; | |
return x / m_to_ft; | |
} | |
double | |
feet_from_metres(double x) | |
{ | |
const double m_to_ft = {3.28084}; | |
return x * m_to_ft; | |
} | |
int | |
main(void) | |
{ | |
double h = 2.4; | |
printf("%lf metres = %lf feet\n", h, feet_from_metres(h)); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment