Search code examples
ctypesc99c11c89

What is the purpose of composite types in C?


People have marked this post as a duplicate of this but it's actually not because I'm not asking what is a composite type but what is its purpose and i gave a use case where it could cause a harm for software developers and then asked if this should be undefined behavior instead.

I was reading that part of the C11 standard about composite types and i was just like : Why the heck on earth would someone do something like that ?

I mean i can't see anything interesting about that. I think this is very confusing for programmers. For the sake of example, let's say we had a function void f() that people used everywhere in the software, they just declare extern void f() and use it. The definition of the function is somewhere programmers don't care about; then one day, one smart guy needed to add an argument to that function and changed the definition to something like void f(int *ptr) {/* ..*/ return *ptr;}. The software will still compile happily but god, all that legacy code that used the old interface is screwed up with segfaults.

The code below is a demo :

/* main.c */
#include <stdio.h>

int f (); 
int p = 5;

int main () 
{
    int r = f ();   /* This call will cause segfault */
    int s = f (&p);

    printf ("r=%d / s=%d \n", r, s);

    return 0;
}


/* another_unit.c */

int f (int *ptr) 
{
    return *ptr;
}

I don't see the purpose of such a thing. In my opinion that should be undefined behavior or at least why do compilers like GCC don't say anything about it ?


Solution

  • The point in your example is that the function f() has no prototype, and the other one has one. The form of declaration without comes from early C and is marked as obsolete since many years.

    The construct of composite type between the two helped when prototypes were introduced into C to accommodate between old code and new code.

    Calling a function with arguments that do not correspond to the parameters that it expects has undefined behavior, so with that mechanism you have to know what you are doing.

    In short, don't use declarations without prototype. They are outdated since long and might be removed from the C standard at any time.