Monday, June 8, 2009

If I could change one thing about C...

If I could change one thing about C, it would be to add the ability to have functions return lists. In other word, I would have added the ability to do this to C:

(int, int) function(int a) {
if(a < 0) {
return (1,a);
} else {
return (-1,-a);
}
}
main() {
int a, b;
(a,b) = function(3);
printf("%d %d\n",a,b);
}

This would have been easy to add; it's a simple matter of having more variables on the stack. There are three ways one can do this with C, all of which I find rather ugly:

int function(int a, int *b) {
if(a < 0) {
*b = a;
return 1;
} else {
*b = -a;
return -1;
}
}
main() {
int a, b;
a = function(3, &b);
printf("%d %d\n",a,b);
}

Or

typedef struct {
int a;
int b; } tuplet;

tuplet function(a) {
tuplet c;
if(a < 0) {
c.a = 1;
c.b = a;
return c;
} else {
c.a = -1;
c.b = -a;
return c;
}
}
main() {
int a, b;
tuplet c;
c = function(3);
a = c.a;
b = c.b;
printf("%d %d\n",a,b);
}

Or

#include <stdint.h>
uint32_t function(int i) {
int16_t a,b;
if(a < 0) {
a = 1;
b = i;
} else {
a = -1;
b = -i;
}
return (a << 16) | b;
}

main() {
int16_t a, b;
uint32_t c;
c = function(3);
a = c >> 16;
b = c & 0xffff;
printf("%d %d\n",a,b);
}

Oh well, there's a reason why Deadwood and MaraDNS 2.0 will probably be my last ever non-OOP C project.