0

I want to represent extended integers and came across _BitInt() but it doesn't work dynamically. I'm trying to do something like this:

void fun(int n)
{
    _BitInt(n)* val = malloc(n); //doesn't work
}  

I understand that everything stored on the stack needs to have its size known at compile time, but I'm mallocing here so I don't understand why this doesn't work

  • Where did you come across `_BitInt()`? It isn't a standard feature AFAIK. – Jonathan Leffler Jul 22 '22 at 10:51
  • Why are you using a compiler-specific extension like `_BitInt`? Why not attempt to find a portable library to solve whatever problem you need solving? And what is the problem you need solving? I mean, why are you using `_BitInt` to begin with? – Some programmer dude Jul 22 '22 at 10:52
  • Since _BitInt(32) is a certain type, and types are a compile-time thing, this certainly wouldn't work. You can write your own library for n-bit integers, or use a library like GMP which does it. – user253751 Jul 22 '22 at 10:57
  • 1
    @JonathanLeffler it's expected to be a [new type in C23](https://en.wikipedia.org/wiki/C2x) but obviously it's fixed-width, not arbitrary-precision and can't be dynamically resized at run time – phuclv Jul 22 '22 at 11:10

1 Answers1

3

First, _BitInt(N) isn't a standard C type. It's a Clang extension and proposed for the next C23 standard. And _BitInt(N) isn't an extended integer type either but a fixed-width integer type. The C standard proposal also says clearly

The original proposal was to name the feature _ExtInt and refer to it in standards text as a “special extended integer type”. However, during committee discussion, the feature was changed to be called a “bit-precise integer type” and so the name _ExtInt was a misnomer.

Being a fixed-width compile time type, the N is part of the type itself (like in C++ templates) and not some variable that modifies the type at run time. Therefore the type BitInt(n) can't be constructed. That also means _BitInt isn't suitable for arbitrary-precision math (dynamic bit width integers in your words)

The fact that you allocated memory dynamically has nothing to do with the type. malloc(n) just allocates a memory region of n bytes and doesn't know about what you're going to store in that region. And you're also doing it wrong, n bytes of memory can store _BitInt(n * CHAR_BIT) and not _BitInt(n)

phuclv
  • 37,963
  • 15
  • 156
  • 475
  • 1
    for future readers: `_BitInt(N)` **is a standard type**, introduced in C23. also a nitpick, but `_BitInt` was never a Clang extension, but rather `_ExtInt` was. – talbi Aug 12 '23 at 16:25