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

  




 

 

Solaris Dynamic Tracing Guide
Previous Next

Conditional Expressions

Although D does not provide support for if-then-else constructs, it does provide support for simple conditional expressions using the ? and : operators. These operators enable a triplet of expressions to be associated where the first expression is used to conditionally evaluate one of the other two. For example, the following D statement could be used to set a variable x to one of two strings depending on the value of i:

x = i == 0 ? "zero" : "non-zero";

In this example, the expression i == 0 is first evaluated to determine whether it is true or false. If the first expression is true, the second expression is evaluated and the ?: expression returns its value. If the first expression is false, the third expression is evaluated and the ?: expression return its value.

As with any D operator, you can use multiple ?: operators in a single expression to create more complex expressions. For example, the following expression would take a char variable c containing one of the characters 0-9, a-z, or A-Z and return the value of this character when interpreted as a digit in a hexadecimal (base 16) integer:

hexval = (c >= '0' && c <= '9') ? c - '0' :
    (c >= 'a' && c <= 'z') ? c + 10 - 'a' : c + 10 - 'A';

The first expression used with ?: must be a pointer or integer in order to be evaluated for its truth value. The second and third expressions may be of any compatible types. You may not construct a conditional expression where, for example, one path returns a string and another path returns an integer. The second and third expressions also may not invoke a tracing function such as trace() or printf(). If you want to conditionally trace data, use a predicate instead, as discussed in Chapter 1, Introduction.

Previous Next

 
 
  Published under the terms fo the Public Documentation License Version 1.01. Design by Interspire