简体   繁体   中英

What does “pointer to register variable” as function parameter do?

As I understand, register specifier hints the compiler to store the variable in a register. This was all fine until I came across the following declaration in XKBlib.h from Xorg-7.7:

extern  int     XkbTranslateKeySym(
    Display *           /* dpy */,
    register KeySym *       /* sym_return */,
    unsigned int        /* modifiers */,
    char *          /* buffer */,
    int             /* nbytes */,
    int *           /* extra_rtrn */
);

Note how sym_return is passed as a pointer to register variable . What makes me wonder is that

  1. this seems allowed, despite the impossibility of taking address of a register variable,
  2. this seems to somehow be important to be mentioned in a function declaration.

Point 1. appears to be somehow invalid, because I appear to be able to pass a pointer to a non- register variable, even with -pedantic-errors flag for GCC.

So, what does this declaration change compared to the one with omitted register keyword? Does it alter calling convention or what?

The register keyword is mostly an obsolete feature in modern C. It does two things:

  • Tell the compiler that it should try to store the variable in a CPU register if possible. The compiler is nowadays much more suited to make such calls than the programmer, hence obsolete feature.
  • Blocks the programmer from taking the address of the variable.

In your case, it says that the pointer itself , not the pointed-at data, should preferably be stored in a register, presumably an address/index register. From a standard C view it doesn't do anything else than that.

It may be that a certain exotic compiler picks a certain calling convention when given register as part of the function, although I have never seen that before. Praxis for calling convention is rather something along the lines of: "if parameter n is a pointer, store it in index register x, if parameter n+1 is a pointer, store it index register y" and the like.

I would suspect that the most likely explanation for the register keyword here is that the programmer didn't know what they were doing. Particularly since no comment about it was left in the header - that's a fairly certain indication of incompetence. Looking at the header as whole, there's lots of other signs supporting the incompetence theory, such as this blatant bug: #define XkbLC_BeepOnComposeFail (1<<31) . When you can find UB within a few minutes of briefly reviewing the source, stay clear of it.

This is not taking the address of register variable, ie it is not a pointer to register variable. Rather it is hinting that the pointer itself (remember, pointers are just variable) should be placed in a register.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM