Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com
Answertopia.com

How To Guides
Virtualization
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
Problem Solutions
Privacy Policy

  




 

 

The GNU C Programming Tutorial - The ?...:... operator

Node:The question mark operator, Next:, Previous:Nested if statements, Up:Decisions



The ?...:... operator

The ?...:... operator is a sort of shorthand if...else... statement. Because it is a little cryptic, it is not often used, but the basic form is as follows:

(condition) ?  expression1 : expression2;

The program evaluates condition. If it is true (not zero), then expression1 is returned; otherwise, expression2 is returned.

For example, in the short program below, the line bas = (foo > bar) ? foo : bar; assigns foo to bas if foo is greater than bar; otherwise, it assigns bar to bas.

#include <stdio.h>

int main()
{
  int foo = 10;
  int bar = 50;
  int bas;

  bas = (foo > bar) ? foo : bar;

  printf("bas = %d\n\n", bas);

  return 0;
}

The program will print bas = 50 as a result.

 
 
  Published under free license. Design by Interspire