bitwise operator variations in C++ - c++

I read C++ provides additional operators to the usual &,|, and ! which are "and","or" and "not" respectively, plus they come with automatic short circuiting properties where applicable.
I would like to use these operators in my code but the compiler interprets them as identifiers and throws an error.
I am using Visual C++ 2008 Express Edition with SP1. How do I activate these operators to use in my code?

If you want to have the 'and', 'or', 'xor', etc keyword versions of the operators made available in MSVC++ then you either have to use the '/Za' option to disable extensions or you have to include iso646.h.

The traditional C++ spelling [*] (just like in C) is && for "logical", short-circuit and, || for "logical", short-circuit or. ! is "logical" not (of course it doesn't short-circuit: what ever would that mean?!-). The bitwise versions are &, |, ~.
According to the C++ standard, the spellings you like (and, or, and so on) should also be implemented, but apparently popular compilers disobey that rule. However you should be able to #include <ciso646> or #include <iso646.h> to hack around that via macros -- see this page, and if your favorite compiler is missing these header files, just create them the obvious way, i.e.,
#define and &&
#define or ||
and so on. (Kudos and gratitude to the commenters for making me research the issue better and find this out!)

Related

What is the difference between "and" and "&&" in c++

Recently I found a code where is used the keyword and which working like &&. So are they both the same or is there any specific condition to use it?
The C++ standard permits the token && to be used interchangeably with the token and.
Not all compilers implement this correctly (some don't bother at all; others require the inclusion of a special header). As such, code using and can be considered idiosyncratic.
The fact that the equivalence is at the token, rather than the operator, level means that since C++11 (where the language acquired the rvalue reference notation), you can arrange things (without recourse to the preprocessor) such that the statement
int and _int(string and vector);
is a valid function prototype. (It's eqivalent to int&& _int(string&& vector).)
As can be seen here, they're the same thing.
No difference. and is just an alternative name for &&.
See https://en.cppreference.com/w/cpp/keyword/and.
There is nothing different in and and &&
The and operator is an alternative representation of the && operator (binary or logical AND).
you can see the complete article here -
http://docwiki.embarcadero.com/RADStudio/Sydney/en/And
What is the difference between "and" and "&&" in c++
The main difference is that and doesn't use the character &.
Otherwise, there is no difference.
is there any specific condition to use it?
Along with other alternative tokens such as the digraphs, it exists in order to allow writing programs on exotic systems with character encoding (such as BCD or ISO 646) that don't have the special symbols such as &.
Unless you're writing on such system where it's necessary to use alternative tokens, you conventionally shouldn't be using them.
They and operator si they name of the &&
The and operator is an alternate to the && operator.

I can't use if ( ifs == NULL) command in VS 2013

When compiling this code:
std::ifstream ifs("somefile.txt");
if(ifs == NULL)
I get an error
no operator matches these operands "=="
I got the same error in every project with VS 2013, but I didn't have any problem in VS 2010.
How to solve this?
The definition of std::basic_ios (from which std::basic_ifstream inherits) changed in C++11. In particular, it's conversion operator operator void* changed to explicit operator bool, so what you're trying to do is no longer valid. Nonetheless, it was never a common way to check the state of your stream. Instead, just do if (!ifs).
The C++ standard changes, now faster than ever, and MSVC has a habit of just mixing together the different standards until they fully support the latest one. You can expect some code to break when things change, although the committee aim to minimise this as much as possible.

Overload ternary ?: operator, or change to if{}else{} in included files

Research project here. In my C++ library, I am including C files:
#include "aprogram.c"
which I execute symbolically by overloading (almost) all operators.
I have to be able to detect (condition) ? this : that and extract condition, this and that for usage in my symbolic execution library. However, SO 1, SO 2 and SO 3 amongst others already helped me realise that ?: cannot be overloaded.
Is there any way for me to forcibly overload ?: anyways?
Can I change all ?: statements in my included C file into ifelse-statements without actually changing the file?
According to the C++ standard you are not permitted to overload ?:
The best you can do is use C macros (but this can lead to horrible code).
Macros were added to the C compiler in the 1970’s to simplify compiler design. Macros are processed by the ‘C Pre-processor’. Unfortunately this pre-processor is naive and does little more than text substitution. The generated code is often unnecessarily complicated, difficult to view (use –E or –P compile option) and hard to debug. Nowadays you should use the compiler to process all of your code (the pre-processor is usually limited to #includes and conditional compilation).
Unfortunately Bjarne Stroustrup decided not to allow you to overload ?: ternary – not for any deep technical reason, but because it was the only tertiary operator and he felt the effort in modifying the compiler was not justified.

Is there any difference between "&&" and "and"? [duplicate]

I am trying to calculate the Greatest Common Denominator of two integers.
C Code:
#include <stdio.h>
int gcd(int x, int y);
int main()
{
int m,n,temp;
printf("Enter two integers: \n");
scanf("%d%d",&m,&n);
printf("GCD of %d & %d is = %d",m,n,gcd(m,n));
return 0;
}
int gcd(int x, int y)
{
int i,j,temp1,temp2;
for(i =1; i <= (x<y ? x:y); i++)
{
temp1 = x%i;
temp2 = y%i;
if(temp1 ==0 and temp2 == 0)
j = i;
}
return j;
}
In the if statement, note the logical operator. It is and not && (by mistake). The code works without any warning or error.
Is there an and operator in C? I am using orwellDev-C++ 5.4.2 (in c99 mode).
&& and and are alternate tokens and are functionally same, from section 2.6 Alternative tokens from the C++ draft standard:
Alternative Primary
and &&
Is one of the entries in the Table 2 - Alternative tokens and it says in subsection 2:
In all respects of the language, each alternative token behaves the same, respectively, as its primary token, except for its spelling. The set of alternative tokens is defined in Table 2.
As Potatoswatter points out, using and will most likely confuse most people, so it is probably better to stick with &&.
Important to note that in Visual Studio is not complaint in C++ and apparently does not plan to be.
Edit
I am adding a C specific answer since this was originally an answer to a C++ question but was merged I am adding the relevant quote from the C99 draft standard which is section 7.9 Alternative spellings <iso646.h> paragraph 1 says:
The header defines the following eleven macros (on the left) that expand
to the corresponding tokens (on the right):
and includes this line as well as several others:
and &&
We can also find a good reference here.
Update
Looking at your latest code update, I am not sure that you are really compiling in C mode, the release notes for OrwellDev 5.4.2 say it is using GCC 4.7.2. I can not get this to build in either gcc-4.7 nor gcc-4.8 using -x c to put into C language mode, see the live code here. Although if you comment the gcc line and use g++ it builds ok. It also builds ok under gcc if you uncomment #include <iso646.h>
Check out the page here iso646.h
This header defines 11 macro's that are the text equivalents of some common operators.
and is one of the defines.
Note that I can only test this for a C++ compiler so I'm not certain if you can use this with a strict C compiler.
EDIT I've just tested it with a C compiler here and it does work.
and is just an alternative token for &&.
We can easily quote the standard here :
2.6 Alternative tokens [lex.digraph]
In all respects of the language, each alternative token behaves the same, respectively, as its primary token, except for its spelling. The set of alternative tokens is defined in Table 2.
In table 2 :
Alternative | Primary
and | &&
But I suggest you to use &&. People used to C/C++ may get confused by and...
Since it is merged now, we are talking also about C, you can check this page ciso646 defining the alternatives tokens.
This header defines 11 macro constants with alternative spellings for those C++ operators not supported by the ISO646 standard character set.
From the C99 draft standard :
7.9 Alternative spellings <iso646.h>
The header defines the following eleven macros (on the left) that expand
to the corresponding tokens (on the right):
and &&
Basically and is just the text version of && in c.
You do however need to #include <iso646.h>. or it isn't going to compile.
You can read more here:
http://msdn.microsoft.com/en-us/library/c6s3h5a7%28v=vs.80%29.aspx
If the code in your question compiles without errors, either you're not really compiling in C99 mode or (less likely) your compiler is buggy. Or the code is incomplete, and there's a #include <iso646.h> that you haven't shown us.
Most likely you're actually invoking your compiler in C++ mode. To test this, try adding a declaration like:
int class;
A C compiler will accept this; a C++ compiler will reject it as a syntax error, since class is a keyword. (This may be a bit more reliable than testing the __cplusplus macro; a misconfigured development system could conceivably invoke a C++ compiler with the preprocessor in C mode.)
In C99, the header <iso646.h> defines 11 macros that provide alternative spellings for certain operators. One of these is
#define and &&
So you can write
if(temp1 ==0 and temp2 == 0)
in C only if you have a #include <iso646.h>; otherwise it's a syntax error.
<iso646.h> was added to the language by the 1995 amendment to the 1990 ISO C standard, so you don't even need a C99-compliant compiler to use it.
In C++, the header is unnecessary; the same tokens defined as macros by C's <iso646.h> are built-in alternative spellings. (They're defined in the same section of the C++ standard, 2.6 [lex.digraph], as the digraphs, but a footnote clarifies that the term "digraph" doesn't apply to lexical keywords like and.) As the C++ standard says:
In all respects of the language, each alternative token behaves the
same, respectively, as its primary token, except for its spelling.
You could use #include <ciso646> in a C++ program, but there's no point in doing so (though it will affect the behavior of #ifdef and).
I actually wouldn't advise using the alternative tokens, either in C or in C++, unless you really need to (say, in the very rare case where you're on a system where you can't easily enter the & character). Though they're more readable to non-programmers, they're likely to be less readable to someone with a decent knowledge of the C and/or C++ language -- as demonstrated by the fact that you had to ask this question.
It is compiling to you because I think you included iso646.h(ciso646.h) header file.
According to it and is identical to &&. If you don't include that it gives compiler error.
The and operator is the text equivalent of && Ref- AND Operator
The or operator is the text equivalent of || Ref.- OR Operator
So resA and resB are identical.
&& and and are synonyms and mean Logical AND in C++. For more info check Logical Operators in C++ and Operator Synonyms in C++.

strcmpi renamed to _strcmpi?

In MSVC++, there's a function strcmpi for case-insensitive C-string comparisons.
When you try and use it, it goes,
This POSIX function is deprecated beginning in Visual C++ 2005. Use the ISO C++ conformant _stricmp instead.
What I don't see is why does ISO not want MSVC++ to use strcmpi, and why is _stricmp the preferred way, and why would they bother to rename the function, and how is a function beginning with an underscore ISO conformant. I know there must be a reason for all this, and I'm suspecting its because strcmpi is non-standard, and perhaps ISO wants non-standard extensions to begin with an _underscore?
ISO C reserves certain identifiers for future expansion (see here), including anything that starts with "str".
IMNSHO, this is Microsoft's way of saying "Do not put Unix software on Windows machines". There are several frustrating aspects to the problem:
strcmpi() is not a POSIX function - the relevant functions are defined in <strings.h> and are called strcasecmp() etc.
Even if you explicitly request support for POSIX functions, Microsoft thinks that you may not use the POSIX names but must prefix them with the wretched underscore.
AFAIK, there isn't a way of overriding the MSVC compiler's view on the issue.
That said, the GCC tool chain gets a bit stroppy about some functions - mktemp() et al. However, it does compile and link successfully, despite the warnings (which are justified).
I note that MSVC also has a bee in its bonnet about snprintf() et al. If their function conformed to the C99 standard (along with the rest of the compiler), then there would never be any risk of an overflow - the standard requires null termination, contrary to the claims of Microsoft.
I haven't got a really good solution to this problem - I'm not sure there is one. One possibility is to create a header (or set of headers) to map all the actual POSIX names to Microsoft's misinterpretation of them. Another is two create a library of trivial functions with the correct POSIX name that each call down onto the Microsoft version of the name (giving you a massive collection of four-line functions - the declarator line, an open brace, a close brace, and a return statement that invokes the Microsoft variant of the POSIX function name.
It's funny how the Microsoft API calls, which also pollute the user's name space, are not deprecated or renamed.
Names begining witth an underscore and a lower case letter are reserved by the C++ Standard for the C++ implementation, if they are declared in the global namespace. This stops them from clashing with similar names in your own code, which must not use this naming convention.
strcmpi goes away altogether in Visual C++ 2008, so you should definitely heed the deprecation if you ever intend to upgrade.
The _ doesn't make the function ISO standard, it's just that functions beginning with _ are safer to add as the language evolves because that's one of the parts of the namespace reserved for the language to use.
According to Microsoft's documentation for _stricmp, it sounds like strcmpi has some practices that result in some unintuitive orderings (including normalizing to lower case instead of simply treating case as irrelevant). Sounds like _stricmp takes more pains to do what one would naturally expect.