Page 1 of 1

Things you probably didn't know about C

Posted: Thu Feb 12, 2009 10:27 pm
by MarauderIIC
Statement: Any single line of code or code enclosed in braces
Expression: Something that resolves to a numeric value (0 for false, nonzero for true)

This is the big one, rest are things you probably did know.
Switch syntax is

switch (expression) statement

Code: Select all

switch (x) {
    case 1:
    while (c < 5) {
        a += 5;
        doSomething();
        case 3:
        c++;
    }
}
^ Doesn't matter where case:s are as long as they're in a switch block.

For syntax is

for (expression1; expression2; expression3) statement
All expressions in for are optional

Code: Select all

for (i < 5;q = q + 1;doSomething());
Equivalent to

Code: Select all

expression1;
while (expression2) {
    statement
    expression3; //except that continue; points to the start of this line
}
Since many humans put the most common case first in an if else, some compilers switch them when they compile in order to save an assembly (don't)JUMP instruction in the most common case.

IE

Code: Select all

            FALSE
        +---------------+ L
        |               v
if (expr) statment1 else statement2
                   |                ^
                   +----------------+ M
                       TRUE

expr
Test
JumpF L
statement1
Jump M
L: statement2
M:

Common-case-first optimization:
Test
JumpT L
statement2
Jump M
L: statement1
M:
In the most common case (expr is true) optimization, instead of reading a JUMP instruction, discarding it, doing the statement, and then jumping, it jumps and then does the statement (notice the lack of discarded jump).

Re: Things you probably didn't know about C

Posted: Fri Feb 13, 2009 11:53 am
by sparda
Nice. The above only refreshed my memory ;)

Here is another cool little thingy:

For conditionals and loops, you can add a prefix-clause and separate it with a comma, then have the
boolean expression come afterward, like so:

Code: Select all

#include <iostream>

int main(void)
{
	int x = 0, y = 0;

	if(x = 1, x == y){}      // x = 1 prefix
	
	while(x = 2, x != 0){   // x = 2 prefix, this would cause an infinite loop since x would be assigned 2, every iteration
                                        // irrespective of the x decrement below.
		printf("Infinite Loop\n");
                x--;
	}
	
	return 0;
	
}

Re: Things you probably didn't know about C

Posted: Mon Feb 16, 2009 1:09 pm
by Scoody
That's use of the magic comma-operator, if someone wondered ...
It evaluates the expressions, returning the value of the rightmost expression

Code: Select all

// Usage: (expression,expression, ..., expression)
int value = 0, value1 = 2, value2 = 2;
value = (value1++,value2 = 4,value1+value2); 
// value is now == 7