473,799 Members | 2,837 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

ternary operator and ostreams

This code works (GCC 3.3.3):

#include <iostream>
int main()
{
bool a = true;
std::cout << "True and false\n"
<< (a == true) ? 't' : 'f';
std::cout << "\n";
return 0;
}

But this code does not:

#include <iostream>

int main()
{
bool a = true;

std::cout << "True and false\n"
<< (a == true) ? 't' : 'f'
<< "\n";

return 0;
}

test.cc: In function `int main()':
test.cc:9: error: invalid operands of types `char' and `const char[2]' to
binary `operator<<'

However, if I enclose the entire ternary expression in parentheses
"((a == true) ? 't' : 'f')" then it does compile.

What is different between these two forms? Both return a char, but
only the latter returns a std::ostream& when used in the above
expression.
Many thanks,
Roger

--
Roger Leigh

Printing on GNU/Linux? http://gimp-print.sourceforge.net/
GPG Public Key: 0x25BFB848. Please sign and encrypt your mail.
Jul 22 '05 #1
6 2265


Roger Leigh wrote:

What is different between these two forms? Both return a char, but
only the latter returns a std::ostream& when used in the above
expression.

Check operator precedence:
(a == true) ? 't' : ('f' << "\n");

Jul 22 '05 #2
In article <87************ @wrynose.whinla tter.uklinux.ne t>, ${roger}
@invalid.whinla tter.uklinux.ne t.invalid says...
This code works (GCC 3.3.3):
[ snipped ]
But this code does not:

#include <iostream>

int main()
{
bool a = true;

std::cout << "True and false\n"
<< (a == true) ? 't' : 'f'
<< "\n";

return 0;
}


This is a precedence problem -- the compiler is trying to treat this as:

(a==true)? 't' : ('f' << '\n');

I.e. trying to shift 'f' left by '\n' bits. This would actually work
(it would typically shift 'f' left by 13 bits) except for one minor
detail: the result of that bit-shift would be an int, and your other
result is 't' which is a char. The compiler does insist that both
results in a ?: be of the same type.

When '<<' is used in its traditional role (bit-shifting) it more or less
makes sense to be able to bit-shift an operand of ?: without extra
parentheses. When you're using it for I/O it usually makes less sense,
but the compiler always give the operand its original precedence and
associativity.

I'd also note that your '==true' is utterly vacuous and kind of stupid
when you think about it -- 'a' starts out as a bool, and your comparison
to true produces a bool that's always equal to a's original value.
Since a is a bool, just use it directly:

std::cout << (a ? 't' : 'f') << "\n";

If you're going to compare it to true, then you probably need to compare
the result of that comparison to true as well -- and so on indefinitely.

Also note that iostreams already support writing bools out in text
format, though they produce 'true' and 'false' instead of the 't' and
'f' you've used.

--
Later,
Jerry.

The universe is a figment of its own imagination.
Jul 22 '05 #3
lilburne <li******@godzi lla.com> writes:
Roger Leigh wrote:
What is different between these two forms? Both return a char, but
only the latter returns a std::ostream& when used in the above
expression.


Check operator precedence:
(a == true) ? 't' : ('f' << "\n");


Doh! How could I have been that unobservant?
Thanks,
Roger

--
Roger Leigh

Printing on GNU/Linux? http://gimp-print.sourceforge.net/
GPG Public Key: 0x25BFB848. Please sign and encrypt your mail.
Jul 22 '05 #4
Jerry Coffin <jc*****@taeus. com> writes:
In article <87************ @wrynose.whinla tter.uklinux.ne t>, ${roger}
@invalid.whinla tter.uklinux.ne t.invalid says...
This code works (GCC 3.3.3):
[ snipped ]
But this code does not:

#include <iostream>

int main()
{
bool a = true;

std::cout << "True and false\n"
<< (a == true) ? 't' : 'f'
<< "\n";

return 0;
}

I'd also note that your '==true' is utterly vacuous and kind of stupid
when you think about it -- 'a' starts out as a bool, and your comparison
to true produces a bool that's always equal to a's original value.
Since a is a bool, just use it directly:

std::cout << (a ? 't' : 'f') << "\n";
That's an excellent point, thanks!
Also note that iostreams already support writing bools out in text
format, though they produce 'true' and 'false' instead of the 't' and
'f' you've used.


That's probably even better. However, I'm constructing SQL database
queries with this, and I want to ensure the "true" and "false" will
never be localised. From what I've seen you need to manually add this
facility to a locale to get localised strings? I want to avoid this
ever occuring if possible.
--
Roger Leigh

Printing on GNU/Linux? http://gimp-print.sourceforge.net/
GPG Public Key: 0x25BFB848. Please sign and encrypt your mail.
Jul 22 '05 #5
In article <87************ @wrynose.whinla tter.uklinux.ne t>, ${roger}
@invalid.whinla tter.uklinux.ne t.invalid says...

[ ... ]
Also note that iostreams already support writing bools out in text
format, though they produce 'true' and 'false' instead of the 't' and
'f' you've used.


That's probably even better. However, I'm constructing SQL database
queries with this, and I want to ensure the "true" and "false" will
never be localised. From what I've seen you need to manually add this
facility to a locale to get localised strings? I want to avoid this
ever occuring if possible.


The default global locale is the "C" locale, which will always spell
these as "true" and "false". If you change the global locale (e.g. with
setlocale) then you may have to explicitly imbue this stream with the
"C" locale again to get the desired behavior. Given that it's crucial
for it to use the "C" locale, you might want to imbue it explicitly even
if (for now) you're never changing locales at all. IIRC, one way to do
that should be something like this:

/* warning: untested code */
std::fstream SQL_stuff("file name.sql");

std::locale def_loc("C");
SQL_stuff.imbue (def_loc);

This way, if you add localization code in the future, you're still
assured that this stream will use the default locale.

--
Later,
Jerry.

The universe is a figment of its own imagination.
Jul 22 '05 #6
Jerry Coffin <jc*****@taeus. com> writes:
In article <87************ @wrynose.whinla tter.uklinux.ne t>, ${roger}
@invalid.whinla tter.uklinux.ne t.invalid says...

[ ... ]
> Also note that iostreams already support writing bools out in text
> format, though they produce 'true' and 'false' instead of the 't' and
> 'f' you've used.


That's probably even better. However, I'm constructing SQL database
queries with this, and I want to ensure the "true" and "false" will
never be localised. From what I've seen you need to manually add this
facility to a locale to get localised strings? I want to avoid this
ever occuring if possible.


The default global locale is the "C" locale, which will always spell
these as "true" and "false". If you change the global locale (e.g. with
setlocale) then you may have to explicitly imbue this stream with the
"C" locale again to get the desired behavior. Given that it's crucial
for it to use the "C" locale, you might want to imbue it explicitly even
if (for now) you're never changing locales at all. IIRC, one way to do
that should be something like this:

/* warning: untested code */
std::fstream SQL_stuff("file name.sql");

std::locale def_loc("C");
SQL_stuff.imbue (def_loc);

This way, if you add localization code in the future, you're still
assured that this stream will use the default locale.


Thanks for clearing that up. I'm currently using "C", and I've
explicitly selected "C" as the default locale, but I hope to
internationalis e it at some point in the near future (I need to clean
up some numeric formatting issues first). I just need to make sure
the communcation with the database (and other programs) is
standardised to use "C".

I'm using std::ostringstr eam to construct the queries, so it'll be no
big deal to explicitly imbue them with "C".
Many thanks for your help,
Roger

--
Roger Leigh

Printing on GNU/Linux? http://gimp-print.sourceforge.net/
GPG Public Key: 0x25BFB848. Please sign and encrypt your mail.
-----= Posted via Newsfeeds.Com, Uncensored Usenet News =-----
http://www.newsfeeds.com - The #1 Newsgroup Service in the World!
-----== Over 100,000 Newsgroups - 19 Different Servers! =-----
Jul 22 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
3836
by: praba kar | last post by:
Dear All, I am new to Python. I want to know how to work with ternary operator in Python. I cannot find any ternary operator in Python. So Kindly clear my doubt regarding this __________________________________ Yahoo! Messenger
6
2767
by: glongword | last post by:
As the assert macro should evaluate to a void expression, it should not have an 'if statement' in its definition. Does this necessitate the existence of a ternary conditional operator? Is there a way assert.h can be implemented without using it? Are these decisions related in anyway?
6
2990
by: Robert Zurer | last post by:
In his paper on Coding Standard found on http://www.idesign.net/idesign/DesktopDefault.aspx Juval Lowy discourages the use of the ternary conditional operator with no specific reason given. I can understand that complicated code would be much less readable using nested operators, but aside from that is there another reason? -- something going on under the hood perhaps which make it inadvisable to use?
48
2765
by: Daniel Crespo | last post by:
Hi! I would like to know how can I do the PHP ternary operator/statement (... ? ... : ...) in Python... I want to something like: a = {'Huge': (quantity>90) ? True : False} Any suggestions?
15
12725
by: Arthur Dent | last post by:
Hi all, im just curious if anyone knows..... With .NET 2, VB didnt happen to get a true ternary operator, did it? Stuck away in a corner somewhere? By ternary, i mean something like C's a?b:c syntax. IIf works in most cases, but in some instances you want to use expressions which may fail if they are evaluated when they arent supposed to be, and it would be nice to have a concise way of writing this instead of using a whole If-Then-Else...
5
3569
by: PerlPhi | last post by:
hi,,, while ago i was wondering why do some programmers rarely uses the ternary operator. wherein it is less typing indeed. i believe in the classic virtue of Perl which is laziness. well let me show you something first before i go to my delimma. codes as follows using Mrs. If Else: #!perl/bin/perl use strict; print "Are you sure you want to quit ('yes' or any key for 'no'): "; chomp($_ = <STDIN>);
4
2390
by: raiderdav | last post by:
I understand how the ternary operator (question mark - ?) works in an if/else setting, but what does it mean when used as a type? For instance, I'm trying to add a get/set in some existing code, but the return type doesn't match: Rectangle? m_textArea = null; public Rectangle TextArea { set { m_textArea = value; } get { return m_textArea; }
3
2430
by: Thomas Lenz | last post by:
The code below should allow to use a comma instead of << with ostreams and include a space between two operands when comma is used. e.g. cout << "hello", "world", endl; should print the line "hello world". #include <iostream> using namespace std;
0
9541
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10482
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10251
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10225
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9072
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6805
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5585
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4139
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3759
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.