I came across an expression in C like
typeof((c) + 1) _tmp = c;
What exactly does this mean?
Thanks for the reply.
Just on
The typeof operator in plain C (not C++) is a GCC addition to the standard. It tells the compiler you want to use the type of the expression enclosed in parenthesis.
Using typeof as above, you can declare variables of types unknown to you or in that context, using another variable's type as reference. It can also be used for casting.
The + operation inside typeof has a peculiar effect. typeof((c) + 1) means "the type of c, or the type of 1, whichever would remain after promotion". Remember that, for example, chars are promoted to ints when used in operations involving ints, ints are promoted to floats, floats to doubles, etc.
So, typeof(int_variable + char_variable) is int, since the char would be promoted to int to perform the operation.
Note that only the compiler can resolve this: typeof doesn't evaluate, it has no value, nothing happens at run-time.
The full description of typeof can be found here.
Compare the code,
typeof((c) + 1) _tmp = c;
with
typeof(c) _tmp = c;
typeof allows arguments of types or variables. Now consider c as,
struct { int a; int b }struct { int a; int b }int.As well as promoting charas per uʍop ǝpısdn, the macro protects against a struct assignment. So the following code will not compile,
struct { int a; int b } c;
typeof((c)+1) _tmp = c;
People may wish to forbid struct assignments for efficiency and code size reasons, especially with-in a generic macro.
Typeof returns a type, and is evaluated at compile time.
The whole statement means declare a variable tmp with the same type as c (usually).
It might declare a related or different type, since the type of c+1 can be different to c. (this is more likely in c++).
It is not standard C. C has no such thing as typeof (unless you are dealing with something user-defined).
typeof is normally a compiler extension (GCC compiler most likely). You can read about it here
http://gcc.gnu.org/onlinedocs/gcc/Typeof.html
create var _tmp st _tmp is of type upcast (max) of c or int and set it to value of c.
eg
char c -> int _tmp // char(c) + 1 is int
float c -> float _tmp // float(c) + 1 is float
In addition to the other answer, the + here is quite subtle. It allows for c to be either an expression or a type.
c is promoted to int (at least)
and the type of the whole expression
has at least integer rank of int.c make it a
cast of the value +1. So then the resulting type is just c.For both kinds of acrobatic it is important that c is of arithmetic type and it is also to note that this trick here might loose the signedness of c. So this use of the typeof extension is not so useful as it might look like. In most cases using uintmax_t or intmax_t would be sufficient.