C Programming Tutorial - Shorthand if else



(test) ? trueCode: falseCode;

lets say we create a computer game and we assign team based on last name

#include <stdio.h>

int main()
{
    char lastName[20];
    printf("Enter your last name: \n");
    scanf(" %s", lastName);
    (lastName[0] <'M') ? you can test characters as same as numbers. Uppercase and lower case matters printf("Blue Team"): printf("Red Team");
  
    return 0;
}

This only work for short codes. Just one line something like this


Lets see another code

I have 0 friends
 I have 1 friend
 I have 2 friends 

#include <stdio.h>

int main()
{
int friends = 1;
printf("I have %d friend%s", friends, (friends != 1) ? "s" : "");
  
    return 0;
}

Comments