1

What's the meaning of -6i in this code?

#include<stdio.h>

int main()
{
    int i = 1234;
    printf("%d",-6i);
}
Michael Burr
  • 333,147
  • 50
  • 533
  • 760
mohan.gade
  • 1,095
  • 1
  • 9
  • 15

2 Answers2

4

To answer your real question, -6i is a complex constant (a GCC extension). From http://gcc.gnu.org/onlinedocs/gcc/Complex.html:

To write a constant with a complex data type, use the suffix 'i' or 'j' (either one; they are equivalent). For example, 2.5fi has type _Complex float and 3i 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 macros I or _Complex_I instead.

So the i in -6i has nothing to do with the variable i, just like the f in the float constant -1.0f would have nothing to do with a variable named f.

A a side note, printf("%d",-6i); is undefined behavior, since the format spec %d doesn't deal with complex arguments. GCC doesn't make any promises (as far as I know) about the representation of a complex type. You can't say much of anything about what that printf() would do.

I think that to print the complex value, you'd have to extract each component of the complex value separately (I don't think glibc's printf() has a format spec extension that deals with GCC's complex types). Something like:

printf("%d %d\n",__real__ -6i, __imag__ -6i);
printf("%f %f\n",__real__ -6.i, __imag__ -6.i);
Michael Burr
  • 333,147
  • 50
  • 533
  • 760
1

Maybe if you change you code a little bit:

int main(){
   int i = 1234;
   printf("%d",-6*i); 
   }

You may get -7404 back.

And to answer the second question, please check this question.

Community
  • 1
  • 1
Tengis
  • 2,721
  • 10
  • 36
  • 58
  • 2
    @MichaelBurr - Tengis's program is different from the OPs. Tengis program will give you `-7404`. That said, Kudos for being the only person to understand OP's question. – user93353 Nov 29 '12 at 18:36