• ### Announcements

#### Archived

This topic is now archived and is closed to further replies.

## Recommended Posts

Ok I''ve read about macros and know what they are and how to use them, but don''t understand something that I see is used commonly. I''ve read beginners stuff about macros, but didn''t find anything that described this, am I missing something simple? Its inside a macro, the ''?'' and '':'' and sybbols. What do they do and how are they used? Eg: #define KEYDOWN(vk_code) ((GetAsyncKeyState(vk_code) & 0x8000) ? 1 : 0) Are these used only in macros? Or have I missed out on something that is used in other areas of c++? (or plain c) Thanks for your time

##### Share on other sites
The ? and : are what''s called the ternary operator (as in unary, binary, ternary) and is defined as:
condition ? true_expression : false_expression
which is (almost) the same as
if (condition)    true_expression;else    false_expression;

It''s valid in C, C++ and Java. It''s useful when you want an if-else construct where you''d not normally be allowed an if-else construct, arguments to functions for example:
printf ("format_string", cond ? "null" : ptr);// my favourite(expr ? fn_a : fn_b) (args);

Skizz

##### Share on other sites
quote:
Original post by julienX
Are these used only in macros? Or have I missed out on something that is used in other areas of c++? (or plain c)

No, you can use it in anywhere you like. They use it in macros because it is short.
int a = 0;bool b = false;// ... some code here// ...a = ( (b) ? (10) : (5) ); // if b is true, a = 10, otherwise, a = 5
PS: parentheses are used to clarify things only, you don't need them.

500

[edited by - alnite on March 4, 2003 6:58:09 PM]

##### Share on other sites
Just be aware that macro stlye functions - like the one shown - are type independant, another way to achieve the same effect as a macro is to create your own inline version of the function which will work the same way as the macro version but has type checking capabilities.

##### Share on other sites
quote:
Original post by Skizz
// my favourite
(expr ? fn_a : fn_b) (args);

Holy cow! Dude! That''s so awful!
Do you really use that much? Someone, take julienX for example, who is not familiar with the ternary operator would never be able to understand that code.

Shawn

• ### Forum Statistics

• Total Topics
627736
• Total Posts
2978869

• 10
• 10
• 21
• 14
• 12