141
votes

I know there is a standard behind all C compiler implementations, so there should be no hidden features. Despite that, I am sure all C developers have hidden/secret tricks they use all the time.

1
  • It'd be great if you/someone were to edit the “question” to indicate the pick of the best hidden features, such as in the C# and Perl versions of this question. Commented May 26, 2010 at 13:19

56 Answers 56

1
2
5
votes

I liked the variable sized structures you could make:

typedef struct {
    unsigned int size;
    char buffer[1];
} tSizedBuffer;

tSizedBuffer *buff = (tSizedBuffer*)(malloc(sizeof(tSizedBuffer) + 99));

// can now refer to buff->buffer[0..99].

Also the offsetof macro which is now in ANSI C but was a piece of wizardry the first time I saw it. It basically uses the address-of operator (&) for a null pointer recast as a structure variable.

1
  • 1
    This is not standard compliant; C99 has 'flexible array members' which achieve the same result and are compliant. (Drop the 1 from the declaration to use a flexible array member.) Commented Jan 18, 2012 at 1:53
5
votes

Lambda's (e.g. anonymous functions) in GCC:

#define lambda(return_type, function_body) \
    ({ return_type fn function_body fn })

This can be used as:

lambda (int, (int x, int y) { return x > y; })(1, 2)

Which is expanded into:

({ int fn (int x, int y) { return x > y } fn; })(1, 2)
4
votes

For clearing the input buffer you can't use fflush(stdin). The correct way is as follows: scanf("%*[^\n]%*c") This will discard everything from the input buffer.

1
  • @Tomas Senart. Do you have a reference of that? I totally agree that you can't use fflush(stdin) in order to clean the buffer, that only works on windows c compiler but does not work in gcc. Commented Jan 27, 2012 at 20:15
3
votes

Early versions of gcc attempted to run a game whenever it encountered "#pragma" in the source code. See also here.

1
  • #pragma GCC poison identifiers This directive bans usage of the identifiers within the program. Poisoned identifiers cannot be #ifdef'd or #undef'd, and attempting to use them for anything will produce an error. Identifiers is a list, separated by spaces. Commented Jul 12, 2010 at 10:14
3
votes

I got shown this in a bit of code once, and asked what it did:


hexDigit = "0123456789abcdef"[someNybble];

Another favorite is:


unsigned char bar[100];
unsigned char *foo = bar;
unsigned char blah = 42[foo];
3
  • First one's too easy. I think you meant someNybble["0123456789abcdef"]. Second one doesn't compile until you add a *. Commented Oct 3, 2008 at 2:43
  • I think the first one's right as-is: it converts the integer someNybble in the range 0-15 to its hex equivalent. Commented Oct 26, 2008 at 0:35
  • Both forms are correct for the 1st, but the one shown is not really tricky, just unusual to see maybe but obvious to understand. Commented Jan 19, 2009 at 0:26
3
votes

Conversion of types by using unusual typecasts. Though not hidden feature, its quite tricky.

Example:

If you needed to know how compiler stores float, just try this:

uint32_t Int;
float flt = 10.5; // say

Int = *(uint32_t *)&flt;

printf ("Float 10.5 is stored internally as %8X\n", Int);

or

float flt = 10.5; // say

printf ("Float 10.5 is stored internally as %8X\n", *(uint32_t *)&flt);

Note the clever use of typecasts. Converting address of variable (here &flt) to desired type (here (uint32_t * )) and extracting its content (applying '*').

This works other side of expression as well:

*(float *)&Int = flt;

This could also be accomplished using union:

typedef union
{
  uint32_t Int;
  float    flt;

} FloatInt_type;
2
  • 3
    This falls under "common usage that I would recommend against". Type aliasing and optimizations don't get along. Use unions instead for clarity, both for the reader and the compiler. Commented Oct 5, 2008 at 0:16
  • To be exact, "don't get along" means "this code might be actually miscompiled", because it's undefined behaviour in C. Commented Jan 19, 2009 at 0:23
3
votes

I only discovered this after 15+ years of C programming:

struct SomeStruct
{
   unsigned a : 5;
   unsigned b : 1;
   unsigned c : 7;
};

Bitfields! The number after the colon is the number of bits the member requires, with members packed into the specified type, so the above would look like the following if unsigned is 16 bits:

xxxc cccc ccba aaaa

Skizz

2
votes

Not really a hidden feature, but it looked to me like voodoo, the first time I saw something like this:


void callback(const char *msg, void *data)
{
    // do something with msg, e.g.
    printf("%s\n", msg);

    return;
    data = NULL;
}

The reason for this construction is, that if you compile this with -Wextra and without the "data = NULL;"-line, gcc will spit out a warning about unused parameters. But with this useless line you don't get a warning.

EDIT: I know there are other (better) ways to prevent those warnings. It just looked strange to me, the first time I saw this.

10
  • Don't you get a warning about unreachable code instead? Why not just comment out 'data' - that also removes the unused param warning. Commented Sep 25, 2008 at 13:15
  • 1
    No, the signature does not change. You just do this: void callback(const char msg, void * / data*/ ) Or this: void callback(const char *msg, void *) Commented Sep 25, 2008 at 14:02
  • 1
    With gcc you could add an unused attribute to parameters: void callback(const char *msg, void *data __attribute__((unused))) Commented Sep 25, 2008 at 14:08
  • 4
    As apposed to using the non-portable attribute syntax. You can just put: (void)data; in the function. I usually put it directly after any locals (as they must be first in c89). I also tend to just make a macro like this: #define UNUSED(x) (void)x so I can just write: UNUSED(data). Commented Sep 25, 2008 at 14:20
  • 1
    You can use '(void)data' anywhere until 'return'. (seems Evan already said that) Commented Sep 25, 2008 at 19:24
2
votes

intptr_t for declaring variables of type pointer. C99 specific and declared in stdint.h

2
votes

Steve Webb has pointed out the __LINE__ and __FILE__ macros. It reminds me of how in my previous job I had hacked them to have in-memory logging.

I was working on a device where there was no port available to pass logging information from device to the PC being used for debugging. One could use breakpoints to halt and know the state of the program using debugger but there was no information on system trace.

Since all calls to debug logs were effectively a single global macro, we changed that macro to dump file name and line number on to a global array. This array contained series of file names and line numbers showing which debug calls were invoked, giving a fair idea of execution trace (not the actual log message though). One could pause the execution by debugger, dump these bytes onto a local file and then map this information to the code base using scripts. This was made possible because we had strict coding guidelines, so we could make had to make changes to the logging mechanism in one file.

2
votes

When comparing a variable to a literal, it is better to put the literal to the left of the == operator, to make the sure the compiler gives an error when you mistakenly use the assignment operator instead.

if (0 == count) {
    ...
}

Might look weird at first glance, but it could save some headache (like if you happened to type if (count = 0) by mistake).

1
  • This is an old trick used religiously by some people, but I believe many compilers generate a warning when they see if (count = 0) making it somewhat redundant. Commented Jan 19, 2012 at 17:44
1
vote

register variables

I used to declare some variables with the register keyword to help speed things up. This would give a hint to the C compiler to use a CPU register as local storage. This is most likely no longer necessary as modern day C compilers do this automatically.

4
  • 3
    More to the point the C compiler knows better than you which variables would benefit most from being in a register. Most modern compilers are smart enough to entirely ignore the register keyword, but if they actually paid attention to it it would probably make your code slower Commented Oct 17, 2008 at 8:45
  • 2
    I am pretty sure some compilers refuse to let you take the address of a variable declared with register. So that is useful, in order to keep your intentions clear. Commented Jun 11, 2009 at 23:00
  • Actually, when you put this to the test, in very specific scenario's with code optimization and perhaps mixed assembly, this keyword does have it merits and can increase speed tremendously. Of course, these are corner cases (one post of me on EE shows just how and when this is useful, but that's a long time ago). Commented Nov 1, 2011 at 17:20
  • Given a combination of a microcontroller and reading the assembly output, this might still be useful in some odd case. Commented Feb 17, 2012 at 7:45
1
vote

Excerpt:

In this page, you will find a list of interesting C programming questions/puzzles, These programs listed are the ones which I have received as e-mail forwards from my friends, a few I read in some books, a few from the internet, and a few from my coding experiences in C.

http://www.gowrikumar.com/c/index.html

1
vote

Say you have a struct with members of the same type:

struct Point {
    float x;
    float y;
    float z;
};

You can cast instances of it to a float pointer and use array indices:

Point a;
int sum = 0, i = 0;
for( ; i < 3; i++)
    sum += ((float*)a)[i];

Pretty elementary, but useful when writing concise code.

2
  • 11
    Are you sure this is portable? I thought that the C standards made no guarantee about structure alignment besides the first element being at offset 0. There might be gaps between the elements. I.e. sizeof(Point) is not guaranteed to be sizeof(float)*3. Commented Jun 22, 2009 at 15:43
  • 1
    @jmtd, Right. In practice its exactly "portable" enough to get you in trouble. The offset of any member other than the first is implementation defined behavior, and need not have the same effective packing as an array of that type. In practice, it is likely it does have the same packing as an array, so this code will work until it is ported to the next platform where it will fail mysteriously. A similar thing happened to a common implementation of MD5 when ported to 64-bit: it compiled and ran, but got a different answer. Commented Aug 1, 2010 at 0:11
1
vote

Here's three nice ones in gcc:

__FILE__ 
__FUNCTION__
__LINE__
1
  • 1
    FILE and LINE are standard ; C99 brings func Commented Nov 29, 2009 at 16:48
1
vote

The size of function pointers is not standard. At least not in the K&R book. Even though it talks about size of other types of pointers but (I think) sizeof of a function pointer is undefined behavior.

Also sizeof is a compile time operator, I see a lot of people asking if sizeof is a function or an operator in online forums.

One error that I have seen is as follows (a simplified example):

int j;
int i;
j = sizeof(i++)

the increment on i would not be executed as sizeof is evaluated at compile time. The programmer intended to hack both operations, increment on i and calculation of sizeof in one statement.

Operator precedence in C governs order of association not order of evaluation. For example if you have three functions f,g,h each returning an int, and their is an expression like:

f() + g() * h()

C standard doesn't give rule about order of evaluation of these functions. Result of g and h would be multiplied before adding result of f. This can lead to error if the functions share state and computation depends on order of evaluation of these functions. This can lead to portability issues.

0
votes

Variable-sized structs, seen in common resolver libs among other places.

struct foo
{
  int a;
  int b;
  char b[1]; // using [0] is no longer correct
             // must come at end
};

char *str = "abcdef";
int len = strlen(str);
struct foo *bar = malloc(sizeof(foo) + len);

strcpy(bar.b, str); // try and stop me!
2
  • In C99 the correct way to declare that is: char b[]; which has the advantage that you do not need to subtract the 1*sizeof b[0] of the size of your struct. Commented Nov 27, 2010 at 12:48
  • 1
    Isn't accessing b[] beyond its declared size undefined behavior, regardless of whether allocated space exists for it? I would think it would be cleaner to use char b[MAX_ARRAY_SIZE] and then subtract MAX_ARRAY_SIZE from the allocation. Better still would have been if zero-size arrays were permitted in the first place, and compilers required to regard them as being a pointer to where the array would start, but without a size limit. Commented Aug 25, 2011 at 21:31
0
votes

Wrap malloc and realloc like this:

#ifdef _DEBUG
#define mmalloc(bytes)                  malloc(bytes);printf("malloc: %d\t<%s@%d>\n", bytes, __FILE__, __LINE__);
#define mrealloc(pointer, bytes)        realloc(pointer, bytes);printf("realloc: %d\t<%s@%d>\n", bytes, __FILE__, __LINE__);
#else //_DEBUG
#define mmalloc(bytes)                  malloc(bytes)
#define mrealloc(pointer, bytes)        realloc(pointer, bytes)

In fact, here is my full arsenol (The BailIfNot is for OO c):

#ifdef _DEBUG
#define mmalloc(bytes)                  malloc(bytes);printf("malloc: %d\t<%s@%d>\n", bytes, __FILE__, __LINE__);
#define mrealloc(pointer, bytes)        realloc(pointer, bytes);printf("realloc: %d\t<%s@%d>\n", bytes, __FILE__, __LINE__);
#define BAILIFNOT(Node, Check)  if(Node->type != Check) return 0;
#define NULLCHECK(var)          if(var == NULL) setError(__FILE__, __LINE__, "Null exception", " var ", FATAL);
#define ASSERT(n)               if( ! ( n ) ) { printf("<ASSERT FAILURE@%s:%d>", __FILE__, __LINE__); fflush(0); __asm("int $0x3"); }
#define TRACE(n)                printf("trace: %s <%s@%d>\n", n, __FILE__, __LINE__);fflush(0);
#else //_DEBUG
#define mmalloc(bytes)                  malloc(bytes)
#define mrealloc(pointer, bytes)        realloc(pointer, bytes)
#define BAILIFNOT(Node, Check)  {}
#define NULLCHECK(var)          {}
#define ASSERT(n)               {}
#define TRACE(n)                {}
#endif //_DEBUG

Here is some example output:

malloc: 12      <hash.c@298>
trace: nodeCreate <hash.c@302>
malloc: 5       <hash.c@308>
malloc: 16      <hash.c@316>
malloc: 256     <hash.c@320>
trace: dataLoadHead <hash.c@441>
malloc: 270     <hash.c@463>
malloc: 262144  <hash.c@467>
trace: dataLoadRecursive <hash.c@404>
2
  • 4
    please, don't like that... for example, this otherwise correct code if (something) mmaloc(); else otherthing; won't compile if _DEBUG is defined. Commented Oct 28, 2009 at 11:24
  • 1
    you want a comma on the malloc macros, not a semicolon (for the reasons @fortran described). That does ignore the return value, though (but then again I'm not sure why these macros are desirable). Commented Jan 5, 2010 at 22:49
0
votes

I just read this article. It has some C and several other languages "hidden features".

1
  • Oh my! they're all stackoverflow contributions, sorry (I'm kinda new here and I didn't notice that there's a hidden features section)... Anyway, it may work as a reference and quick guide to these topics. Commented Jun 22, 2009 at 6:34
0
votes

Object oriented C macros: You need a constructor (init), a destructor (dispose), an equal (equal), a copier (copy), and some prototype for instantiation (prototype).

With the declaration, you need to declare a constant prototype to copy and derive from. Then you can do C_OO_NEW. I can post more examples if needed. LibPurple is a large object oriented C code base with a callback system (if you want to see one in use)

#define C_copy(to, from) to->copy(to, from)

#define true 1
#define false 0
#define C_OO_PROTOTYPE(type)\
void type##_init (struct type##_struct *my);\
void type##_dispose (struct type##_struct *my);\
char type##_equal (struct type##_struct *my, struct type##_struct *yours); \
struct type##_struct * type##_copy (struct type##_struct *my, struct type##_struct *from); \
const type type##__prototype = {type##_init, type##_dispose, type##_equal, type##_copy

#define C_OO_OVERHEAD(type)\
        void (*init) (struct type##_struct *my);\
        void (*dispose) (struct type##_struct *my);\
        char (*equal) (struct type##_struct *my, struct type##_struct *yours); \
        struct type##_struct *(*copy) (struct type##_struct *my, struct type##_struct *from); 

#define C_OO_IN(ret, type, function, ...)       ret (* function ) (struct type##_struct *my, __VA_ARGS__);
#define C_OO_OUT(ret, type, function, ...)      ret type##_##function (struct type##_struct *my, __VA_ARGS__);

#define C_OO_PNEW(type, instance)\
        instance = ( type *) malloc(sizeof( type ));\
        memcpy(instance, & type##__prototype, sizeof( type ));

#define C_OO_NEW(type, instance)\
        type instance;\
        memcpy(&instance, & type ## __prototype, sizeof(type));

#define C_OO_DELETE(instance)\
        instance->dispose(instance);\
        free(instance);

#define C_OO_INIT(type)         void type##_init (struct type##_struct *my){return;}
#define C_OO_DISPOSE(type)      void type##_dispose (struct type##_struct *my){return;}
#define C_OO_EQUAL(type)        char type##_equal (struct type##_struct *my, struct type##_struct *yours){return 0;}
#define C_OO_COPY(type)         struct type##_struct * type##_copy (struct type##_struct *my, struct type##_struct *from){return 0;}
0
votes

I like the typeof() operator. It works like sizeof() in that it is resolved at compile time. Instead of returning the number of bytes, it returns the type. This is useful when you need to declare a variable to be the same type as some other variable, whatever type it may be.

typeof(foo) copy_of_foo; //declare bar to be a variable of the same type as foo
copy_of_foo = foo; //now copy_of_foo has a backup of foo, for any type

This might be just a gcc extension, I'm not sure.

2
  • 1
    in the same familly there is also an offsetof(), well it's a macro but it's nice anyway. Commented May 8, 2010 at 8:25
  • 1
    And if you want: #define countof(array) (sizeof (array) / sizeof (array[0])) ;) Commented May 10, 2010 at 19:53
0
votes

Use NaN for chained calculations / error return :

//#include <stdint.h>
static uint64_t iNaN = 0xFFF8000000000000;
const double NaN = *(double *)&iNaN; // quiet NaN

An inner function can return NaN as an error flag : it can safely be used in any calculation, and the result will always be NaN.

note : testing for NaN is tricksy, since NaN != NaN... use isnan(x), or roll your own.
x!=x is mathematically correct if x is NaN, but tends to get optimised out by some compilers

1
  • Rather then casting hex constants, I prefer to get NaN by nonsignalling floating division of zero by zero. Commented May 26, 2011 at 2:27
0
votes

The often forgotten %n specifier in printf format string can be quite practical sometimes. %n returns the current position of the imaginary cursor used when printf formats its output.

int pos1, pos2;
 char *string_of_unknown_length = "we don't care about the length of this";

  printf("Write text of unknown %n(%s)%n text\n", &pos1, string_of_unknown_length, &pos2);
  printf("%*s\\%*s/\n", pos1, " ", pos2-pos1-2, " ");
  printf("%*s", pos1+1, " ");
  for(int i=pos1+1; i<pos2-1; i++)
    putc('-', stdout);
  putc('\n', stdout);

will have following output

Write text of unknown (we don't care about the length of this) text
                      \                                      /
                       --------------------------------------

Granted a little bit contrived but can have some uses when making pretty reports.

0
votes

How about using while(0) inside a switch so you can use continue statements like break :-)

void sw(int s)
{
    switch (s) while (0) {
    case 0:
        printf("zero\n");
        continue;
    case 1:
        printf("one\n");
        continue;
    default:
        printf("something else\n");
        continue;
    }
}
0
-1
votes

In Visual Studio, it is possible for you to highlight your own defined types.

To do that, create a file called "usertype.dat" in the folder "Commom7/IDE". The contents of that file shall be the types you want to highlight. For example:

//content of usertype.dat

int8_t
int16_t
int32_t
int64_t
uint8_t
uint16_t
uint32_t
uint64_t
float32_t
float64_t
char_t
1
2

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.