Reputation: 33
When I write the following C code, I find that (contrary to what I expected), gcc can accept this code and compile it successfully! I don't know why for it seems it is a wrong statement.
int main() {
int a = 1i;
return 0;
}
I guess it may be accepting 1i
as a complex number. Then int a = 1i
means int a = 0+1i
and 1i
is not a valid integer so it only accepts the 0
.
int main() {
int a = 1i*1i;
printf("%d\n",a);
return 0;
}
I tried the code above and found that it printa -1. Maybe my thought is correct. But this is the first time I find that the C compiler can do this work. Is my guess correct?
Upvotes: 3
Views: 96
Reputation: 224082
Your intuition is correct. gcc allows for complex number constants as an extension.
From the gcc documentation:
To write a constant with a complex data type, use the suffix
i
orj
(either one; they are equivalent). For example,2.5fi
has type_Complex float
and3i
has type_Complex int
. Such a constant always has a pure imaginary value, but you can form any complex value you like by adding one to a real constant. This is a GNU extension; if you have an ISO C99 conforming C library (such as GNU libc), and want to construct complex constants of floating type, you should include <complex.h> and use the macrosI
or_Complex_I
instead.
So 1i
is the complex number i. Then when you assign it to a
, the complex part is truncated and the real part is assigned (and if the real part is a floating point type, that would be converted to int
).
This conversion is spelled out in section 6.3.1.7p2 of the C standard:
When a value of complex type is converted to a real type, the imaginary part of the complex value is discarded and the value of the real part is converted according to the conversion rules for the corresponding real type.
Upvotes: 6