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

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

Related

result of evaluating block statement in c++

I have the simplest c++ statement declaring a variable "a":
int a = ({ int b = 10; b; });
As recent gcc and clang says, it's a valid statement which really declares variable a having value 10.
The question is: what is this? I know about various types of expressions. I know about various types of statements. But I can't find in a c++ 14 standard any mentioning that "block statement as an expression returns latest inner evaluated expression" or something like this.
Could somebody please point me exact lines of a standard saying that is code line is fully valid?
The question is: what is this?
This is a GNU extension to ISO standard C, an extension that is available also for C++, but likewise is not part of ISO C++.
Citing the GCC Manual: Chapter 6 - Extensions to the C Language Family:
...
These extensions are available in C and Objective-C. Most of them are also available in C++. ...
Statement Exprs: Putting statements and declarations inside expressions.
Where the latter is explained in detail in GCC Manual: Section 6.1 - Statements and Declarations in Expressions:
A compound statement enclosed in parentheses may appear as an expression in GNU C. This allows you to use loops, switches, and local variables within an expression.
Recall that a compound statement is a sequence of statements surrounded by braces; in this construct, parentheses go around the braces. For example:
({ int y = foo (); int z;
if (y > 0) z = y;
else z = - y;
z; })
is a valid (though slightly more complex than necessary) expression for the absolute value of foo ().
...
As for Clang, the Clang Language Extensions describes that Clang aims to support many GCC extensions: [emhpasis mine]:
This document describes the language extensions provided by Clang. In addition to the language extensions listed here, Clang aims to support a broad range of GCC extensions. Please see the GCC manual for more information on these extensions.

(v) is actually (*&v) since when?

Could C++ standards gurus please enlighten me:
Since which C++ standard version has this statement failed because (v) seems to be equivalent to (*&v)?
I.e. for example the code:
#define DEC(V) ( ((V)>0)? ((V)-=1) : 0 )
...{...
register int v=1;
int r = DEC(v) ;
...}...
This now produces warnings under -std=c++17 like:
cannot take address of register variable
left hand side of operand must be lvalue
Many C macros enclose ALL macro parameters in parentheses, of which the above is meant only to be a representative example.
The actual macros that produce warnings are for instance
the RTA_* macros in /usr/include/linux/rtnetlink.h.
Short of not using/redefining these macros in C++, is there any workaround?
If you look at the revision summary of the latest C++1z draft, you'd see this in [diff.cpp14.dcl.dcl]
[dcl.stc]
Change: Removal of register storage-class-specifier.
Rationale: Enable repurposing of deprecated keyword in future
revisions of this International Standard.
Effect on original feature: A valid C++ 2014 declaration utilizing the register
storage-class-specifier is ill-formed in this International Standard.
The specifier can simply be removed to retain the original meaning.
The warning may be due to that.
register is no longer a storage class specifier, you should remove it. Compilers may not be issuing the right error or warnings but your code should not have register to begin with
The following is a quote from the standard informing people about what they should do with regards to register in their code (relevant part emphasized), you probably have an old version of that file
C.1.6 Clause 10: declarations [diff.dcl]
Change: In C++, register is not a storage class specifier.
Rationale: The storage class specifier had no effect in C++.
Effect on original feature: Deletion of semantically well-defined feature.
Difficulty of converting: Syntactic transformation.
How widely used: Common.
Your worry is unwarranted since the file in question does not actually contain the register keyword:
grep "register" /usr/include/linux/rtnetlink.h
outputs nothing. Either way, you shouldn't be receiving the warning since:
System headers don't emit warnings by default, at least in GCC
It isn't wise to try to compile a file that belongs to a systems project like the linux kernel in C++ mode, as there may be subtle and nasty breaking changes
Just include the file normally or link the C code to your C++ binary. Report a bug if you really are getting a warning that should normally be suppressed to your compiler vendor.

Difference in the style of giving comments between C and C++

Is there any difference between a commenting style between C(/*..*/) and C++(//)?
MISRA C:2004 says
Rule 2.2 (required): Source code shall only use /* … */ style
comments.
Note: This Rule is revoked for MISRA C:2012 when support for C99 was added
MISRA C++ says
Rule 2.7.1 (required): The character sequence /* shall not be used
with c style comments.
Rule 2.7.3 says suggested comment as // for c++
Can any one explain why MISRA says to use /* in C and // in C++?
The MISRA C clause you quote requires that "line comments" of the form
// This is a line comment
not be used, in favour of a "C-style" comment of the form
/* Original C style comment
Can extend across multiple lines
*/
This allows older compilers to be used, since the "line comment" was only introduced in 1999, and was only available with some compilers before then as a non-standard extension.
The MISRA C++ clause you quote (from memory, there is a similar one in MISRA C) requires that the "original C-style comment" shall not be nested. So, this is discouraged
/* Warning: non-standard nesting of comment
/* Nested comment
*/
*/
This is discouraged because support for it is not standard, but some compilers can be configured to support it. Code which uses "nested comments" can therefore behave differently (including compiling with one compiler, but not with another) and in unintended ways. However, code without nested comments will compile as intended, regardless of whether or not the compiler supports nested comments.
There isn't a problem with nesting of "line comments", since the // causes the compiler to ignore everything to end of line. This is okay in C++, since (unlike C) all C++ versions (even pre-standard) support "line comments". (This is not necessarily true if digraphs or trigraphs are used, but MISRA also discourages using them).
Rule 2.2 means C only allows /**/ comments, while rules 2.7.1 tells not to nest C comments, by forbidding the use /* in a C comment. They are unrelated.
C89 had only /* ... */ for comments. But C++ style comments // .. were added to C in C99. I think MISRA simply attempts to keep it consistent so that the C++ style comments do not become an issue if you are compiling the C code in C89/C90.
But this rarely matters anymore as both styles of comments are supported in both modern C and C++.
You can read the MISRA rationale for the reasoning:
MISRA-C-2004 rationale:
Rule 2.3 (required): The character sequence /* shall not be used
within a comment.
C does not support the nesting of comments even though some compilers
support this as a language extension. A comment begins with /*
and continues until the first */ is encountered. Any /* occurring
inside a comment is a violation of this rule.
Consider the following code fragment: /* some comment, end comment
marker accidentally omitted <>
Perform_Critical_Safety_Function(X); /* this comment is not compliant
*/
In reviewing the page containing the call to the function, the
assumption is that it is executed code. Because of the accidental
omission of the end comment marker, the call to the safety
critical function will not be executed.
MISRA-C++ 2008 rationale:
Rule 2-7-1 The character sequence /* shall not be used within a
C-style comment.
C++ does not support the nesting of C-style comments even though some
compilers support this as a non-portable language extension. A comment
beginning with /* continues until the first */ is encountered. Any
/* occurring inside a comment is a violation of this rule.
Although // were an incredibly common non-standard extension to C90 compilers, it was never allowed by the C90 standard. The rationale for the MISRA rule is that you should follow the applicable language standard.
So it's quite simple:
MISRA-C:2004 is for C90 which only allowed /* */ comments.
MISRA-C++:2008 is for C++, which allows // comments (no matter C++ version)
MISRA-C:2012 is for C99 which allows // comments.
Because of the above, the rule you refer to has been removed in MISRA-C:2012. Consider upgrading to the 2012 MISRA version, as it has been improved in many ways.
In short, those standards are to help the programmers from getting inconsistent compiler behaviors due to the comment style when they compile their codes using different compiler standards.
This is the rationale behind the standards.
More elaborated answer:
This is because the // line comment is not supported before C99 standard. While MISRA-C 2004 document is created to support C89/C90 standard.
Rule 2.2 (required): Source code shall only use /* … */ style
comments.
This excludes the use of // C99 style comments and C++ style
comments, since these are not permitted in C90. Many compilers support
the // style of comments as an extension to C90. The use of // in
preprocessor directives (e.g. #define) can vary. Also the mixing of /*
… */ and // is not consistent. This is more than a style issue, since
different (pre C99) compilers may behave differently
Check Lundin's answer on this post. Also, check this SO post on C line commenting before C99.
Thus, that explain why the MISRA-C 2004 clause you post requires /* to be used.
With the same idea, the MISRA-C++ 2008 standard discourages the use of /* - C-Style (multiline) comment - in C++ since some compilers may generate errors. It encourages to use // since it is the "original" C++ comment style.
From MISRA C 2004:
Rule 2.2 (required): Source code shall only use /* … */ style comments.
This excludes the use of // C99 style comments and C++ style comments, since these are not
permitted in C90. Many compilers support the // style of comments as an extension to C90. The
use of // in preprocessor directives (e.g. #define) can vary. Also the mixing of /* … */ and //
is not consistent. This is more than a style issue, since different (pre C99) compilers may behave differently.
I think this explains it all, but I'll still add my explanation with links.
In original C (pre C99), there were no // comments. C++ introduced a double slash comment prefix // as a way to comment single lines.
For more clarity, let's go line by line:
This excludes the use of // C99 style comments and C++ style comments, since these are not
permitted in C90.
Nowadays, modern compilers like gcc have started supporting such // in C90 mode also, but will still issue a warning like:
warning: C++ style comments are not allowed in C90
but it is recommended to use /*..*/ comments in C90 C.
Many compilers support the // style of comments as an extension to C90.
That is what I exactly told above, but it is still not recommended to use // in C90 C as the code will not be portable. For example, that code will compile with gcc, but with another compiler which does not have the extension, it will not compile.
The
use of // in preprocessor directives (e.g. #define) can vary.
I think the meaning of this is clear. It says that the usage of // is not going to be consistent in preprocessor directives.
Also the mixing of /* ... */ and //
is not consistent.
How? This is possible. Like I mentioned above, it varies from compiler to compiler. In C99 C, it will be mostly consistent, but if you're talking about the pre C99 compilers, it matters if they support or not support // comments.
This is more than a style issue, since different (pre C99) compilers may behave differently.
Yes it is. As this is MISRA 2004, which is mainly talking about pre C90 C mainly. This is because most C90 compilers do not support //, and thus you will get an error. If you're using C99, this is invalid.
Questions Expected
Why was there no // in pre C99 C, and then why was it introduced in C++? Is there a specific reason?
C originated from B. B originated from BCPL. // were created during BCPL, and thus BCPl used them. It's successor B started using /*...*/, which were inherited by C. Although, C++ decided to resurrect the BCPL comments, and of course used /*...*/ also. The C-standard at that time took // as a non-standard feature.
When C99 C was introduced, it had the comments //.
What are // and /*...*/ comments called?
// comments are called single-line comments as they can only extend till one line.
/*...*/ comments are called multi-line comments as they can extend upto multiple lines.
Is it compulsory to use only one kind of comment through your source code?
No, you can use any and even both. Although, some people say that using only one type makes the code readable. It is more a matter of opinion.
Is rule 2.2 of MISRA C 2004 outdated?
Kind of. Recently, MISRA 2012 was released which has these changes. Although, if you think that MISRA C 2004 is wrong as it is only concentrating on pre C99, it isn't. I would recommend using MISRA 2012 nowadays.
Rule 2.7.1 (required): The character sequence /* shall not be used with c style comments.
(emphasis added)
I think you are just misreading the meaning of the word "with" in the above rule and interpreting in the sense "shall not be used for c style comments".
Perhaps the rule would be more clear if the word "within" were used rather than "with".

Is there a valid C++11 program with the expression 'C++11'?

The name of the programming language C++ derives from the parent language C and the ++ operator (it should arguably be ++C) and, hence, the expression C++ may naturally occur in C++ programs. I was wondering whether you can write a valid C++ program using the 2011 standard (without extensions) and containing the expression C++11 not within quotes and after pre-processing (note: edited the requirement, see also answer).
Obviously, if you could write a C++ program prior to the 2011 standard with the expressions C++98 or C++03, then the answer is a trivial yes. But I don't think that was possible (though I don't really know). So, can it be done with the new armory of C++11?
NO if we require the characters C++11 to be outside any literal, after preprocessing -- because at translation phase 7 the three tokens will be identifier, ++ and integer-literal
The first two tokens are a postfix-expression, the later is a primary.
There is no reduction in the grammar that can contain these two nonterminals in sequence, so any program containing C++11 will fail syntax analysis.
However, if you do not consider character literals to be strings, then the answer is YES as you can contain it in a wide character literal:
int main()
{
wchar_t x = L'C++11';
}
which does not use the preprocessor or a string literal, and the construct is required to be supported by the standard:
The value of a wide-character literal containing multiple c-chars is implementation-defined.
So, can it be done with the new armory of C++11?
No.
Define “valid C++ program”.
The C++ standard defines a “well-formed C++ program” as “a C++ program constructed according to the syntax rules, diagnosable semantic rules, and the One Definition Rule”. This leaves open the possibility of C++ programs that are not well-formed. (C explicitly has the notion of programs that are conforming but not strictly conforming, e.g., that use extensions of a particular compiler.)
If you consider it valid to use extensions, then you can implement a C++ compiler that permits C++11 in some context.

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!)