mikeage.net Logo

mikeage.net @ ב׳ שבט תשע״ח

Posts Tagged ‘C’

Conditional Assignments

‍‍כ״ד תשרי תשס״ז - Sunday, October 15th, 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.

Preprocessor #s, ##s, and other weird stuff

‍‍כ״א תשרי תשס״ז - Friday, October 13th, 2006

In the post on strings for enums , I used two types of pound symbols in the preprocessor macros: # and ##. Here's some more detail:

i++ Incremements and Execution Sequence

‍‍ט״ז תשרי תשס״ז - Saturday, October 7th, 2006


What will the following code print?

int i = 5;
printf("%d ", i++ * i++);
printf("%d\n", i);


Multiple Pointer Declarations

‍‍י״ד תשרי תשס״ז - Friday, October 6th, 2006

Quick quiz:

What does the following code do:

char* p1, p2


Creating an array of strings for an enum

‍‍י״ב תשרי תשס״ז - Tuesday, October 3rd, 2006

A common issue in writing C based test tools is the desire to be able to show a user a list of all enums. This, of course, is technically impossible, as the mapping from enum to int is one way only. However, the following trick lets you create a two dimensional character array who's index is the enum (cast to int, to be pedantic) is an index to a string containing the name of the enum.

Quick Map
Content +
Personal +
Archives +
Site Stuff +
RBS Weather +
Search +
Recent Images

Valid XHTML 1.1!
Printer Friendly Page

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

Memory(TRUE): 4194304/4194304
Memory(FALSE): 3028288/3038272