In the process of studying, this idea of ​​using typedef appeared:

#include<stdio.h> typedef int height; typedef int width; typedef int mul; mul sq(height,width); int main(){ width h=5;/*or 'int' or other type*/ width w=17; printf("%d\n",sq(h,w)); } mul sq(height h,width w){ return h * w; } 

but the chip failed. And, as expected, I received not what I wanted. I realized that in my example the function is similar to this:

  int sq(int h,int w){ return h * w; } 

And it would be desirable that when accepting a function of the wrong type, there would be an error or a compiler warning. How to implement it?

  • You can wrap the structure. - Kirill Malyshev
  • Not quite clear what I would like. - Enikeyshchik
  • In Go, this approach has already been implemented. - Witold
  • If you compile gcc, you can use __builtin_choose_expr(__builtin_types_compatible_p(...)) in macro format. - NewView
  • typedef does not define a new type, but merely introduces a synonym. If you want to determine the full type, then you road in C ++. - freim

1 answer 1

In the C language, the creation of custom types capable of carrying arbitrary data is possible only through the definition of new struct types, array types or enum types. Enum-types in C are always integer and freely convertible among themselves, which makes them unsuitable for solving this problem. Array types are poorly suited, tend to degrade to pointers, and are uncopyable, which makes them unsuitable for solving this problem, too.

There are only struct types. We'll have to wrap the values ​​in a struct with one field. This, however, will make the code rather overloaded with repetitive syntactic details. Compound literals and, possibly, _Generic will help make the code more elegant, but they still won't be able to turn C into C ++. So the question is how much you want it.

 #include <stdio.h> typedef struct { int value; } height; typedef struct { int value; } width; typedef struct { int value; } area; area sq(height h, width w) { return (area) { h.value * w.value }; } int main() { width h = { 5 }; width w = { 17 }; height h2 = { 5 }; // printf("%d\n", sq(h, w).value); printf("%d\n", sq(h2, w).value); } 
  • But enum 'ohm, you can set the maximum size, within the sizeof(int) course. - NewView