mikeage.net Logo
mikeage.net/2006/10/15/

mikeage.net @ כ"ד מרחשון תשס"ט

Archive for כ"ד תשרי תשס"ז - October 15, 2006

Conditional Assignments

כ"ד תשרי תשס"ז - October 15, 2006

Sometimes, you'll have a scenario with two variables, and you need to use one of them based on a simple test. Rather than a long and awkward if / else statement, C allows the use of the ? : form. It is perfectly acceptable to write:

int i,j,k,l;
...
i = (j > 5? k : l)

which will set i to k if j is greater than 5, and l otherwise.
Another common use is [sf]?printf statements:

printf("The test %s\n",(status == OK) ? "passed" : "failed");

However, one can't use it to handle selective assignments. The following code is illegal:

int i,j,k;
...
((i>5) ? j : k) = 5;

This cannot be used to choose whether j or k is set to 5.
There is, however a way this can be done. Using pointer, we can select which one to deference:

*((i>5) ? &j : &k) = 5;

This will work.

Quick Map
Content +
Personal +
Archives +
Site Stuff +
RBS Weather +
Search +
New Images
Visitors
Clustermap

Valid XHTML 1.1!
Printer Friendly Page
 

Last Modified: September 04, 2006 @ 05:11 CST

Memory(TRUE): 2621440/2621440
Memory(FALSE): 2495920/2504160