What is the difference between "and" and "&&" in c++ - 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.

Related

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.

Exiting from the Middle of an Expression Without Using Exceptions

Solved: I figured out a clean way to do it with setjmp()/longjmp(), requiring only a minimal wrapper like:
int jump(jmp_buf j, int i) { longjmp(j, i); return 0; }
This allows jump() to be used in conditional expressions. So now the code:
if (A == 0) return;
output << "Nonzero.\n";
Is correctly translated to:
return
((A == 0) && jump(caller, 1)),
(output << "Nonzero.\n"),
0;
Where caller is a jmp_buf back to the point of invocation in the calling function. Clean, simple, and efficient to a degree that is far less implementation-defined than exceptions. Thank you for your help!
Is there a way to emulate the use of flow-control constructs in the middle of an expression? Is it possible, in a comma-delimited expression x, y, for y to cause a return?
Edit: I'm working on a compiler for something rather similar to a functional language, and the target language is C++. Everything is an expression in the source language, and the sanest, simplest translation to the destination language leaves as many things expressions as possible. Basically, semicolons in the target language become C++ commas. In-language flow-control constructs have presented no problems thus far; it's only return. I just need a way to prematurely exit a comma-delimited expression, and I'd prefer not to use exceptions unless someone can show me that they don't have excessive overhead in this situation.
The problem of course is that most flow-control constructs are not legal expressions in C++. The only solution I've found so far is something like this:
try {
return
x(), // x();
(1 ? throw Return(0) : 0); // return 0;
} catch (Return& ret) {
return ref.value;
}
The return statement is always there (in the event that a Return construct is not reached), and as such the throw has to be wrapped in ?: to get the compiler to shut up about its void result being used in an expression.
I would really like to avoid using exceptions for flow control, unless in this case it can be shown that no particular overhead is incurred; does throwing an exception cause unwinding or anything here? This code needs to run with reasonable efficiency. I just need a function-level equivalent of exit().
You may want to research cfront, which is a program from the late 80's/early 90's that translated C++ into C (no templates or exceptions back then), because there were few, if any, native C++ compilers.
The way it handled inline functions is very similar to what you are trying to do: lots of trinary (?:) operators, commas, and parentheses. However, it could not convert an inline function with control flow more complex than if/then, e.g. a for or while loop, to an expression, and would have to implement that function as non-inline.
The only way to "prematurely exit a comma-delimited expression" would be with the trinary operator and parentheses. For example:
(
first thing,
second thing,
test expression?
(
next thing if successful,
another thing,
return value
)
:( // How often can you use an emoticon as an operator, anyway?
something to do if unsuccessful,
more cleanup,
return value
)
)
If the compiler doesn't short-circuit the then and else clauses of the trinary operator, you're out of luck.
what for? C++ is imperative language. Expressions there are just expressions. Use functional languages if you want to do everything as expressions/functions.
I get the feeling you just have a functional specification (in terms of pre- and post-conditions, for example) of how the translation process must be performed. Since C++ is not a declarative language, but an imperative one, you have to derive yourself a procedural implementation of that translation process before you start coding. And, as you have already seen, it's not as simple as concatenating all your original expressions using commas.
What you are trying to do is have the C++ compiler do your work for you. This won't work, since C++ is not a declarative language, and its compiler won't dynamically try to interpret what you meant from your specifications. And, if this could work, C++ would have to be just another dynamic declarative language, and you would be probably targeting another static language.
A hint on what could work: Analyze every original expression completely (with its possible side-effects) and only then output code. If your expression is compound (it has sub-expressions), don't output anything until you have analyzed the bigger expression.

What is the purpose of the ## operator in C++, and what is it called?

I was looking through the DXUTCore project that comes with the DirectX March 2009 SDK, and noticed that instead of making normal accessor methods, they used macros to create the generic accessors, similar to the following:
#define GET_ACCESSOR( x, y ) inline x Get##y() { DXUTLock l; return m_state.m_##y;};
...
GET_ACCESSOR( WCHAR*, WindowTitle );
It seems that the ## operator just inserts the text from the second argument into the macro to create a function operating on a variable using that text. Is this something that is standard in C++ (i.e. not Microsoft specific)? Is its use considered good practice? And, what is that operator called?
Token-pasting operator, used by the pre-processor to join two tokens into a single token.
This is also standard C++, contrary to what Raldolpho stated.
Here is the relevant information:
16.3.3 The ## operator [cpp.concat]
1 A ## preprocessing token shall not
occur at the beginning or at the end
of a replacement list for either form
of macro definition.
2 If, in the
replacement list, a parameter is
immediately preceded or followed by a
## preprocessing token, the parameter is replaced by the corresponding
argument’s preprocessing token
sequence.
3 For both object-like and
function-like macro invocations,
before the replacement list is
reexamined for more macro names to
replace, each instance of a ##
preprocessing token in the replacement
list (not from an argument) is deleted
and the preceding preprocessing token
is concatenated with the following
preprocessing token. If the result is
not a valid preprocessing token, the
behavior is undefined. The resulting
token is available for further macro
replacement. The order of evaluation
of ## operators is unspecified.
It's a preprocessing operator that concatenates left and right operands (without inserting whitespace). I don't think it's Microsoft specific.
This isn't Standard C++, it's Standard C. Check out this Wikipedia article.
And is it a good practice? In general, I hate pre-processor macros and think they're as bad as (if not worse than) Goto.
Edit: Apparently I'm being misunderstood by what I meant by "This isn't Standard C++, it's Standard C". Many people are reading the first phrase and failing to read the second. My intent is to point out that macros were inherited by C++ from C.
As Mehrdad said, it concatenates the operands, like:
#define MyMacro(A,B) A ## B
MyMacro(XYZ, 123) // Equivalent to XYZ123
Note that MISRA C suggests that this operand (and the # 'stringify' operand) should not be used due to the compiler dependent order of calculation.
It is token pasting operator allowed by Standard C++ (see 16.3.3 for details).
As for good practice: using macro is not a good practice IMHO (in C++).
it's the concatenation for macro arguments i.e.
GET_ACCESSOR (int, Age);
will be expended to
inline int GetAge() { DXUTLock l; return m_state.m_Age;};

bitwise operator variations in 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!)

Alternative Keyword Representations

The C++ standard (ISO/IEC 14882:03) states the following (2.11/2):
Furthermore, the alternative
representations shown in Table 4 for
certain operators and punctuators
(2.5) are reserved and shall not be
used otherwise:
and, and_eq, bitand, bitor, compl,
not, not_eq, or, or_eq, xor, xor_eq
I have tried using these with multiple compilers without problems.
From my understanding I'm only forbidden to use these as identifier names.
English isn't my first language, so it would be nice if someone could verify that I can indeed use these bit-wise mnemonics in expressions (i.e., "int i = not 0;").
EDIT: I should probably point out that I'm not going to obscure code by using these (if they are valid). It's just for general knowledge. =)
Thanks!
Yes, you can use them as alternative to name tokens. For example:
struct foo {
// defines a destructor
compl foo() { }
};
Your example would work too. It would however store an one into i. If you want to use bitwise not, you use compl (~):
int i = compl 0;