0

I was making a complex number calculator using struct, here is my printf function

printf("%d%c%di", sum.real, sign, sum.imag);

I can everything correct except one thing, when the sum.imag part is 1 or -1 ofcourse it prints out "1i" or "-1i" respectively, is there a way apart from using a lot of "if"s that i can format the printf function where if sum.imag is 1 or -1 it shouldn't print the value instead print just the "i"??

user3564573
  • 680
  • 1
  • 12
  • 24
  • If sounds like you want to embed an `if` statement into the format string itself, which, as far as I know, isn't possible. – DanielGibbs Nov 21 '14 at 09:16
  • IMO, to achieve this, you don't need `lot of "if"s`... single `if..else` based on `sum.imag ` will do. – Sourav Ghosh Nov 21 '14 at 09:17
  • As @SouravGhosh said you could use 1 if like `if(sum.imag == 1 || sum.imag == -1 ) printf("%d%ci", sum.real, sign); else printf("%d%c%di", sum.real, sign, sum.imag);` – bitcell Nov 21 '14 at 09:19

1 Answers1

1

I don't think you can do this with your format string; you'll have to use an if statement:

if (sum.imag == 1 || sum.imag == -1) {
    printf("%d%ci", sum.real, sign);
} else {
    printf("%d%c%di", sum.real, sign, sum.imag);
}

Alternatively you could use a ternary expression for the format string, but this would be a quite a bit more unreadable, and is actually undefined behaviour although it should work on most modern compilers, although they will produce a warning about the (sometimes) unused argument. You can read more about this on this question.

printf((sum.imag == 1 || sum.imag == -1) ? "%d%ci" : "%d%c%di"), sum.real, sign, sum.imag);
Community
  • 1
  • 1
DanielGibbs
  • 9,910
  • 11
  • 76
  • 121
  • 2
    the second example is undefined behaviour. – mch Nov 21 '14 at 09:24
  • if sum.imag is 1 or -1 your printf looks like `printf("%d%ci", sum.real, sign, sum.imag);`, so you have only 2 format specifier, but 3 parameters, which is undefined behaviour. there is also a `)` too much in this line. – mch Nov 21 '14 at 09:30
  • Sure. But on most modern compilers it will give a warning but still work as expected. I've updated the answer to mention that this is undefined behaviour and included a link to a question about extra `printf` arguments. – DanielGibbs Nov 21 '14 at 09:59