Home > Software engineering >  How to use register storage class with typedef?
How to use register storage class with typedef?

Time:04-16

I want to do this:

typedef register unsigned int _newint;

Basically, a concise alias of register unsigned int as _newint.

But an error, "more than one storage class may not be specified," occurs, underlining register.

I want to know if I can do this or not; if yes then how?

CodePudding user response:

I want to know if I can do this or not, if yes then how?

Both typedef and register count as storage classes, though that's somewhat of a technicality in the case of typedef. You cannot declare any identifier to have more than one storage class, so the direct answer is no, you cannot do that.

You could conceivably use a macro instead of a typedef to achieve a similar effect:

#define _newint register unsigned int

void foo() {
    _newint x;
}

That is misleading, however, so you shouldn't.

More generally, you probably should not be using register storage class at all. Modern compilers don't need your help to figure out which variables to store in registers, and register is just a hint, so the only notable effect is that you are prevented (by rule) from taking the address of an object declared with that storage class.

CodePudding user response:

Strange as it may seem, the typedef keyword is actually a storage class specifier (and, as the error message indicates, you can't have a second, register specifier in the same statement). From this C11 Draft Standard:

6.7.1 Storage-class specifiers


5     The typedef specifier is called a ‘‘storage-class specifier’’ for syntactic convenience only; it is discussed in 6.7.8. The meanings of the various linkages and storage durations were discussed in 6.2.2 and 6.2.4.

If, despite the wording in the above-quoted paragraph, you find this inconvenient, then consider why you want to add a storage class specifier to a typedef. Most likely, it will make for clearer code if you add the register specifier (or any other qualifier) to actual variables, when they are declared:

typedef unsigned int _newint;

void foo(void)
{
    register _newint MyNewInt;
    //...
}

'Hiding' that register specifier in an alias may cause problems for future readers of your code, who then can't understand why adding a different specifier to a variable of that type causes problems.

  • Related