Alternative Keyword Representations - c++

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;

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.

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++.

Why using define or static const? [duplicate]

Is it better to use static const vars than #define preprocessor? Or maybe it depends on the context?
What are advantages/disadvantages for each method?
Pros and cons between #defines, consts and (what you have forgot) enums, depending on usage:
enums:
only possible for integer values
properly scoped / identifier clash issues handled nicely, particularly in C++11 enum classes where the enumerations for enum class X are disambiguated by the scope X::
strongly typed, but to a big-enough signed-or-unsigned int size over which you have no control in C++03 (though you can specify a bit field into which they should be packed if the enum is a member of struct/class/union), while C++11 defaults to int but can be explicitly set by the programmer
can't take the address - there isn't one as the enumeration values are effectively substituted inline at the points of usage
stronger usage restraints (e.g. incrementing - template <typename T> void f(T t) { cout << ++t; } won't compile, though you can wrap an enum into a class with implicit constructor, casting operator and user-defined operators)
each constant's type taken from the enclosing enum, so template <typename T> void f(T) get a distinct instantiation when passed the same numeric value from different enums, all of which are distinct from any actual f(int) instantiation. Each function's object code could be identical (ignoring address offsets), but I wouldn't expect a compiler/linker to eliminate the unnecessary copies, though you could check your compiler/linker if you care.
even with typeof/decltype, can't expect numeric_limits to provide useful insight into the set of meaningful values and combinations (indeed, "legal" combinations aren't even notated in the source code, consider enum { A = 1, B = 2 } - is A|B "legal" from a program logic perspective?)
the enum's typename may appear in various places in RTTI, compiler messages etc. - possibly useful, possibly obfuscation
you can't use an enumeration without the translation unit actually seeing the value, which means enums in library APIs need the values exposed in the header, and make and other timestamp-based recompilation tools will trigger client recompilation when they're changed (bad!)
consts:
properly scoped / identifier clash issues handled nicely
strong, single, user-specified type
you might try to "type" a #define ala #define S std::string("abc"), but the constant avoids repeated construction of distinct temporaries at each point of use
One Definition Rule complications
can take address, create const references to them etc.
most similar to a non-const value, which minimises work and impact if switching between the two
value can be placed inside the implementation file, allowing a localised recompile and just client links to pick up the change
#defines:
"global" scope / more prone to conflicting usages, which can produce hard-to-resolve compilation issues and unexpected run-time results rather than sane error messages; mitigating this requires:
long, obscure and/or centrally coordinated identifiers, and access to them can't benefit from implicitly matching used/current/Koenig-looked-up namespace, namespace aliases etc.
while the trumping best-practice allows template parameter identifiers to be single-character uppercase letters (possibly followed by a number), other use of identifiers without lowercase letters is conventionally reserved for and expected of preprocessor defines (outside the OS and C/C++ library headers). This is important for enterprise scale preprocessor usage to remain manageable. 3rd party libraries can be expected to comply. Observing this implies migration of existing consts or enums to/from defines involves a change in capitalisation, and hence requires edits to client source code rather than a "simple" recompile. (Personally, I capitalise the first letter of enumerations but not consts, so I'd be hit migrating between those two too - maybe time to rethink that.)
more compile-time operations possible: string literal concatenation, stringification (taking size thereof), concatenation into identifiers
downside is that given #define X "x" and some client usage ala "pre" X "post", if you want or need to make X a runtime-changeable variable rather than a constant you force edits to client code (rather than just recompilation), whereas that transition is easier from a const char* or const std::string given they already force the user to incorporate concatenation operations (e.g. "pre" + X + "post" for string)
can't use sizeof directly on a defined numeric literal
untyped (GCC doesn't warn if compared to unsigned)
some compiler/linker/debugger chains may not present the identifier, so you'll be reduced to looking at "magic numbers" (strings, whatever...)
can't take the address
the substituted value need not be legal (or discrete) in the context where the #define is created, as it's evaluated at each point of use, so you can reference not-yet-declared objects, depend on "implementation" that needn't be pre-included, create "constants" such as { 1, 2 } that can be used to initialise arrays, or #define MICROSECONDS *1E-6 etc. (definitely not recommending this!)
some special things like __FILE__ and __LINE__ can be incorporated into the macro substitution
you can test for existence and value in #if statements for conditionally including code (more powerful than a post-preprocessing "if" as the code need not be compilable if not selected by the preprocessor), use #undef-ine, redefine etc.
substituted text has to be exposed:
in the translation unit it's used by, which means macros in libraries for client use must be in the header, so make and other timestamp-based recompilation tools will trigger client recompilation when they're changed (bad!)
or on the command line, where even more care is needed to make sure client code is recompiled (e.g. the Makefile or script supplying the definition should be listed as a dependency)
My personal opinion:
As a general rule, I use consts and consider them the most professional option for general usage (though the others have a simplicity appealing to this old lazy programmer).
Personally, I loathe the preprocessor, so I'd always go with const.
The main advantage to a #define is that it requires no memory to store in your program, as it is really just replacing some text with a literal value. It also has the advantage that it has no type, so it can be used for any integer value without generating warnings.
Advantages of "const"s are that they can be scoped, and they can be used in situations where a pointer to an object needs to be passed.
I don't know exactly what you are getting at with the "static" part though. If you are declaring globally, I'd put it in an anonymous namespace instead of using static. For example
namespace {
unsigned const seconds_per_minute = 60;
};
int main (int argc; char *argv[]) {
...
}
If this is a C++ question and it mentions #define as an alternative, then it is about "global" (i.e. file-scope) constants, not about class members. When it comes to such constants in C++ static const is redundant. In C++ const have internal linkage by default and there's no point in declaring them static. So it is really about const vs. #define.
And, finally, in C++ const is preferable. At least because such constants are typed and scoped. There are simply no reasons to prefer #define over const, aside from few exceptions.
String constants, BTW, are one example of such an exception. With #defined string constants one can use compile-time concatenation feature of C/C++ compilers, as in
#define OUT_NAME "output"
#define LOG_EXT ".log"
#define TEXT_EXT ".txt"
const char *const log_file_name = OUT_NAME LOG_EXT;
const char *const text_file_name = OUT_NAME TEXT_EXT;
P.S. Again, just in case, when someone mentions static const as an alternative to #define, it usually means that they are talking about C, not about C++. I wonder whether this question is tagged properly...
#define can lead to unexpected results:
#include <iostream>
#define x 500
#define y x + 5
int z = y * 2;
int main()
{
std::cout << "y is " << y;
std::cout << "\nz is " << z;
}
Outputs an incorrect result:
y is 505
z is 510
However, if you replace this with constants:
#include <iostream>
const int x = 500;
const int y = x + 5;
int z = y * 2;
int main()
{
std::cout << "y is " << y;
std::cout << "\nz is " << z;
}
It outputs the correct result:
y is 505
z is 1010
This is because #define simply replaces the text. Because doing this can seriously mess up order of operations, I would recommend using a constant variable instead.
Using a static const is like using any other const variables in your code. This means you can trace wherever the information comes from, as opposed to a #define that will simply be replaced in the code in the pre-compilation process.
You might want to take a look at the C++ FAQ Lite for this question:
http://www.parashift.com/c++-faq-lite/newbie.html#faq-29.7
A static const is typed (it has a type) and can be checked by the compiler for validity, redefinition etc.
a #define can be redifined undefined whatever.
Usually you should prefer static consts. It has no disadvantage. The prprocessor should mainly be used for conditional compilation (and sometimes for really dirty trics maybe).
Defining constants by using preprocessor directive #define is not recommended to apply not only in C++, but also in C. These constants will not have the type. Even in C was proposed to use const for constants.
Always prefer to use the language features over some additional tools like preprocessor.
ES.31: Don't use macros for constants or "functions"
Macros are a major source of bugs. Macros don't obey the usual scope
and type rules. Macros don't obey the usual rules for argument
passing. Macros ensure that the human reader sees something different
from what the compiler sees. Macros complicate tool building.
From C++ Core Guidelines
As a rather old and rusty C programmer who never quite made it fully to C++ because other things came along and is now hacking along getting to grips with Arduino my view is simple.
#define is a compiler pre processor directive and should be used as such, for conditional compilation etc.. E.g. where low level code needs to define some possible alternative data structures for portability to specif hardware. It can produce inconsistent results depending on the order your modules are compiled and linked. If you need something to be global in scope then define it properly as such.
const and (static const) should always be used to name static values or strings. They are typed and safe and the debugger can work fully with them.
enums have always confused me, so I have managed to avoid them.
Please see here: static const vs define
usually a const declaration (notice it doesn't need to be static) is the way to go
If you are defining a constant to be shared among all the instances of the class, use static const. If the constant is specific to each instance, just use const (but note that all constructors of the class must initialize this const member variable in the initialization list).

What is it called when a block returns a value?

I came across this code recently, which doesn't look legal to me (but gcc compiles it). I don't so much mind the construction as want a name for it:
#define MAX(a,b) \
({ \
typeof(a) _a = (a); \
typeof(b) _b = (b); \
(_a > _b) ? (_a) : (_b); \
})
Apparently, the last statement's value is being returned as the "value" of the expression bounded by the namespace.
Edit: Thanks for the answers guys. Turns out this is an extension to plain C called Statement Expressions.
It is not a namespace, it is a macro which returns maximum of two values.
\ at the end of the statements is use to append multiple statements and create a multi-line macro.
The code is not standard C++ but it compiles in gcc because it is supported as an gcc compiler extension.
Good Read:
Statement Expressions:
A compound statement is a sequence of statements enclosed by braces. In GNU C, a compound statement inside parentheses may appear as an expression in what is called a Statement expression.
.--------------.
V |
>>-(--{----statement--;-+--}--)--------------------------------><
The value of a statement expression is the value of the last simple expression to appear in the entire construct. If the last statement is not an expression, then the construct is of type void and has no value.
Note: This excerpt is taken from IBM XL C/C++ v7.0 documentation.
This is called a statement expression, and is a non-standard extension of GCC. It allows you to use a compound statement as an expression, with a value given by the last expression in the compound statement.
It's used here to avoid the problem that function-like macros may evaluate their arguments multiple times, giving unexpected behaviour if those evaluations have side-effects. The macro is carefully written to evaluate a and b exactly once.
In C++, you should never need to do anything like this - use function templates instead:
template <typename T> T max(T const & a, T const & b) {
return a > b ? a : b;
}
First of all, it is not Standard C++, because typeof is an extension to C++, by GCC. There is another extension, called Statement Extension is used in the code.
Compile your code with -pedantic option, it will not compile.
As for the question, it is not namespace. It is just a macro, which gives you maximum of two values.
This a macro, just like any other #DEFINE. Essentially, the compiler replaces MAX(a,b) with the code defined therein. This will return the max value.
The {} operators, in this context, are an "anonymous scope operator" (aka "lexical enclosure," "form," and various other things. They're being used, somewhat akin to a namespace, to limit the scope of _a and _b to within the braces, so they won't conflict with other vars you might have with the same names. "auto" vars defined within the {braces} will be "destroyed" after the closing brace is reached; or, on a non-local transfer, like a "return" or "longjmp". You can't, however, reliably use "goto" to broach them.
You're probably only used to seeing them after "if," "do," "while," and "for" operators, but think of it as a way to generally "bundle" multiple statements into one "slot," just as you would to run multiple statements as the "then" or "else" clause of an "if" (where, leaving out the braces, you have only one statement "slot")
As Mike Seymour pointed out, the ({}) operation is a non-standard GCC extension, which returns the value of the last item evaluated within it. It's very similar to the general scoping operator, except the inherent return at the end.
This may be seen as off topic, but the title of this question came up in my web search while looking for a way to return a value from a {} block. Then I realized how to do it from standard c++ constructs. I post this for the next person who lands here for the same reason.
To pick up on what #BRPocock said, lo these 8 years ago, it is possible to return a value from a “anonymous scope operator” / “lexical enclosure” — hence use a {} block as part of an expression — through the use of lambda functions.
(Historical aside: all of the binding forms in Lisp can be written in terms of macros using lambda expressions. Lisp is where the modern term “lambda function” comes from. Lisp was John McCarthy's 1959 procedural embodiment of the theoretical “lambda calculus” of Church and Turning.)
Back to c++, this is a minimal anonymous lambda function, with no lexical capture, no arguments, and an empty body:
[](){}
This is that function applied to no arguments:
[](){}()
Here is that function call with some statements in its body:
[](){ int i=2; int j=3; return i+j; }()
There is some extra “stuff” around it (which could be encapsulated with a macro) and it requires explicit use of return, but it meets the basic functionality of returning a value from a {} block. For example this will print 5:
std::cout << [](){ int i=2; int j=3; return i+j; }() << std::endl;

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;};