May 21, 2009 11:21
struct
Saw a cool way to initialize structs in C yesterday:
struct employee {
char *name;
char *surname;
int age;
};
struct employee emp = {
.name = "John",
.surname = "Smith",
.age = 20
};
Invaluable when initializing large structures, where it is very easy to forget the correct order. Much more clear too.
I seriously need to get my hands on C's specs.
comma operator
The comma operator executes statements from it's left to right and yields the rightmost statement.
I've always used it in for loop to initialize more than one variable, like:
for (i = 0, j = 10; ...
But I never realized it's full potential. Recently, I saw such a use of it:
while (cin >> ival, !cin.eof()) ...
It has a very low precedance, I think it may even be in the very end of precedance table, so
i = printf("1\n"), printf("22\n"), printf("333\n");
printf("i=%i\n", i-1);
prints i=1, and
i = (printf("1\n"), printf("22\n"), printf("333\n"));
printf("i=%i\n", i-1);
prints i=3.
UPD. More precisely, what happens here is that: the assignment operator has a higher precedence over the comma operator, and has a right to left associativity, so the i = printf("1\n") is executed first, then, the first comma operator is executed, and it yields printf("22\n"), then the second comma operator is excuted, which yields printf("333\n").
while i still remember,
note,
c,
fun,
programming