C program syntax

Viewed 85

I am working on an old C code repo that has some weird syntax that I have never seen.

char (*__kaboom)[NUM_ELEMS( Port ) ] = NULL;

How does this work? what does __kaboom do and how can we use it say for example in a print statement?

And other places like these

char (*name)[MAX] = NULL;
name = (char (*)[MAX]) malloc(MAXB*sizeof(char));

I am new to C programming and appreciate your suggestion. Thanks

3 Answers

Most likely, NUM_ELEMS(Port) is a macro that expands to (sizeof(Port)/sizeof(Port[0])) or something similar. If so, it only works properly when the argument is the name of an array defined in the source file (not declared extern and defined in another file) that is not a function parameter. Whatever it is, it must expand to an integer constant, or to nothing.

The notation:

char (*variable)[SIZE] = NULL;

is declaring a pointer to an array of the given size and type, and setting the pointer to NULL.

The definition and cast in the second fragment are conceptually similar.

The name __kaboom is reserved for the implementation to use. Note that you should not, in general, create function, variable, tag or macro names that start with an underscore. Part of C11 §7.1.3 Reserved identifiers says:

  • All identifiers that begin with an underscore and either an uppercase letter or another underscore are always reserved for any use.
  • All identifiers that begin with an underscore are always reserved for use as identifiers with file scope in both the ordinary and tag name spaces.

See also What does double underscore (__const) mean in C?

In this declaration

char (*__kaboom)[NUM_ELEMS( Port ) ] = NULL;

there is declared a pointer to an array of the type char[NUM_ELEMS( Port ) ].

Here is a demonstrative program.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void) 
{
    char s[] = "Hello";
    
    char ( *p )[sizeof( s )] = NULL;
    
    p = ( char ( * )[sizeof( s )] )malloc( sizeof( char ) * sizeof( s ) );
    
    strcpy( *p, s );
    
    puts( *p ); 

    free( p );
    
    return 0;
}

The program output is

Hello

That is if you have an array like

char s[N];

then a pointer to such an array can be declared like

char ( *p )[N] = &s;

Or you can assign the address of a dynamically allocated memory for an array of the type char[N] (or char [MAX] as in your example) to the pointer

p = ( char ( * )[N] ) malloc( N * sizeof( char ) );

Dereferencing the pointer you will get the pointed array (lvalue).

  1. define __kaboom as pointer to array of NUM_ELEMS( Port ) char elements and initialize it to NULL (BTW identifiers are not allowed to start with __)
  2. define name as pointer to array of MAX char elements and initialize it to NULL
  3. Assign pointer from the point 2. with reference to memory allocated by the malloc function.
Related