Search code examples
cprintftext-formatting

Conditional inside `printf` statement


Is there a way to shorten this:

if (a > 0)
    printf("%d", a);
else
    printf("%d", -a);

I mean, is there a way to write all this inside one printf with the ? operator?


Solution

  • This should work for you:

    printf("%d", (a > 0? a: -a));
    

    Input/Output:

     5 -> 5
    -5 -> 5
    

    A little test program:

    #include<stdio.h>
    
    int main() {
    
        int a = -5, b = 5;
    
        printf("%d\n", (a > 0? a: -a));
        printf("%d\n", (b > 0? b: -b));
    
        return 0;
    
    }