My question regarding underscores in names is partly answered here, but either the answer is incomplete or I do not fully understand it.
Sect. 2.14.8.7 of the C++11 standard declares this literal operator as an example:
long double operator "" _w(long double);
Besides declaring the operator, the standard and its example do two further things that, if viewed separately, each make sense:
it begins the name _w with an underscore; and
it puts the operator in the global namespace.
My question has two parts:
According to the answer linked above, the name _w is not an identifier, or the identifier _w is not a name, or ... well, I'm confused.
If _w is okay, then is the capitalized _W okay, too -- as in 60.0_W, meaning 60.0 watts? Or is the preprocessor likely to mishandle the capitalized version?
Undoubtedly like you, I am not in the habit of starting global names with underscores, a habit the standard's sect. 17.6.4.3.2.1 explicitly seems to deprecate. Therefore, if you can cast some additional light on the matter of underscores, names and literal operators, the light would be appreciated.
Alright, I checked back with Richard Smith from the Clang team, and the _W part in your literal operator is indeed not a reserved identifier and/or name and it is also a seperate preprocessor token which will get expanded if it names a macro. This is in accordance with the standard subclauses 2.5, where an identifier is a preprocessor-token, and 2.2 which has macro expansion as part of phase 4, before preprocessor-tokens are replaced with just tokens of the language grammar, which happens in phase 7.
He also mentioned that, since the Portland meeting of the committee, you can say operator""_W, which will prevent macro expansion, since the _W is not a single identifier anymore. Clang trunk already implements this and compiles the following snippet:
#define _W _x
int operator""_W(unsigned long long){ return 42; }
int main(){
int i = 1337_W;
}
Related
At [over.literal] I read, in the list of examples, that
double operator""_Bq(long double);
is valid, whereas
double operator"" _Bq(long double);
is ill-formed, which is apparently a consequence of the space right after "".
Now, from the linked page, I can easily get to [usrlit.suffix] with one click and I read that
Literal suffix identifiers that do not start with an underscore are reserved for future standardization.
Good, but where do I read why operator"" _Bq is invalid?
I've also read the description of user-defined-string-literal on cppreference, but to be honest I've found it a bit confusing.
Can anybody break that down with examples?
"" _Bq is a string-literal followed by an identifier, whereas ""_Bq is a user-defined-string-literal which is a single, distinct preprocessing token ([lex.pptoken]).
As a consequence, the former is affected by macro expansion, but the latter is not:
#define _x
int operator "" _x(char); // becomes `int operator "" (char);` which is invalid
int operator ""_x(char); // ok
That aside, both forms are allowed as part of a literal-operator-id and have the same meaning. However, since forming the first construct involves the use of a reserved identifier, it is ill-formed with no diagnostic required per [lex.name]/3 (motivation for this being that _Bq could be in use by the implementation as a macro).
That's the intent, anyway. The current normative wording does not actually make that difference clear enough: user-defined-string-literal ultimately contains an identifier, and [lex.name]/3 has no indication that it only applies to identifiers that are themselves preprocessing tokens. This is the subject of CWG2521.
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++.
void operator"" test( const char* str, size_t sz )
{
std::cout<<str<<" world";
}
int main()
{
"hello"test;
return 0;
}
In GCC 4.7, this generates "warning: literal operator suffixes not preceded by '_' are reserved for future standardization [enabled by default]"
I understand why this warning is generated, but GCC says "enabled by default".
Is it possible to disable this warning without just disabling all warnings via the -w flag?
After reading several comments to this question, I reviewed the C++ 11 Standard (non-final draft N3337).
When I said "I understand why this warning is generated" I was mistaken.
I assumed that an underscore was not technically required by the standard, but just a recommendation (hence the warning rather than an error).
But as Nicol Bolas has brought up, the standard uses the following language when speaking about user defined literals:
"Literal suffix identifiers that do not start with an underscore are reserved for future standardization." usrlit.suffix
"Some literal suffix identifiers are reserved for future standardization; see [usrlit.suffix]. A declaration whose literal-operator-id uses such a literal suffix identifier is ill-formed, no diagnostic required." over.literal
This is similar to the language used for reserved identifiers and the "alternative representations" such as "and", "or", "not". I think this makes it pretty clear that this shouldn't actually be a warning in the first place, but an error.
This may not be the direct answer to the question of "is it possible to disable", but it is answer enough for me.
For what it is worth, -Wno-literal-suffix silences this warning since gcc-7 (see here live on godbold), i.e. this option also turns off warnings for user defined literal operators without leading underscore:
-Wliteral-suffix (C++ and Objective-C++ only)
...
Additionally, warn when a user-defined literal operator is declared with a literal suffix identifier that doesn’t
begin with an underscore. Literal suffix identifiers that don’t begin
with an underscore are reserved for future standardization.
However, one should stick to the advice in #cmeub's answer and rather avoid using literal suffix identifiers without underscore, as it leads to ill formed programs.
Someone pointed out to me that I had what looks like a typo in some c++ code:
protected:
Foo x, y,;
I would have thought the trailing comma would be an error, but apparently it isn't? Is this undefined, or what happens? Presumably something bad, since a code-checker program complained about it.
The relevant grammar production is in §9.2:
member-declarator-list:
member-declarator
member-declarator-list , member-declarator
The comma is only allowed to separate the declarators (names). member-declarator may not itself contain a comma.
EDIT: here is member-declarator… it's not quite as self-contained, the syntax for declarators is in general a cobweb.
member-declarator:
declarator virt-specifier-seq(opt) pure-specifier(opt)
declarator brace-or-equal-initializer(opt)
identifier(opt) attribute-specifier-seq(opt) : constant-expression
Incorrect grammar is not undefined behavior; a compiler allowing a misplaced comma has a bug. Rejecting that sort of thing is a requirement of the standard.
Note, trailing commas are allowed in enumeration definitions and brace-initializers. I think both cases were added by C++11 to simplify writing source code generators. (The preprocessor, which most often gets that job, has a tough time even with such simple requirements.) Typically a simple generator might avoid creating declarations with multiple names, because due to the complicated grammar, it's a can of worms. On the other hand, an empty declaration consisting of ; is allowed, as is a semicolon after a member function definition.
My observations
GCC 4.6.2:
void myFunc()
{
int x, y, ; // <-- Syntax error
}
But
class MyClass
{
int x, y,; // <-- No error (one extra comma) but last comma is ignored
};
MSVC 2008:
Both of them make errors
OpenWatcom 1.8:
Both of them make errors
What is the meaning of "qualifier" and the difference between "qualifier" and "keyword"?
For the volatile qualifier in C and we can say that volatile is a keyword, so what is the meaning of "qualifier"?
A qualifier adds an extra "quality", such as specifying volatility or constness of a variable. They're similar to adjectives: "a fickle man", "a volatile int", "an incorruptible lady", "a const double". With or without a qualifier, the variable itself still occupies the same amount of memory, and each bit has the same interpretation or contribution to the state/value. Qualifiers just specify something about how it may be accessed or where it is stored.
keywords are predefined reserved identifiers (arguably, see below) that the language itself assigns some meaning to, rather than leaving free for you to use for your own purposes (i.e. naming your variables, types, namespaces, functions...).
Examples
volatile and const are both qualifiers and keywords
if, class, namespace are keywords but not qualifiers
std, main, iostream, x, my_counter are all identifiers but neither keywords nor qualifiers
There's a full list of keywords at http://www.cppreference.com/wiki/keywords/start. C++ doesn't currently have any qualifiers that aren't keywords (i.e. they're all "words" rather than some punctuation symbols).
Where do qualifiers appear relative to other type information?
A quick aside from "what does qualifier mean" into the syntax of using a qualifier - as Zaibis comments below:
...[qualifiers] only qualify what follows [when] there is nothing preceding. so if you want a const pointer to non-const object you had to write char * const var...
A bit (lot?) about identifiers
identifiers themselves are lexical tokens (distinct parts of the C++ source code) that:
begin with a alpha/letter character or underscore
continue with 0 or more alphanumerics or underscores
If it helps, you can think of identifiers as specified by the regexp "[A-Za-z_][A-Za-z_0-9]*". Examples are "egg", "string", "__f", "x0" but not "4e4" (a double literal), "0x0a" (that's a hex literal), "(f)" (that's three lexical tokens, the middle being the identifier "f").
But are keywords identifiers?
For C++, the terminology isn't used consistently. In general computing usage, keywords are a subset of identifiers, and some places/uses in the C++11 Standard clearly reflect that:
"The identifiers shown in Table 4 are reserved for use as keywords" (first sentence in 2.12 Keywords)
"Identifiers that are keywords or operators in C++..." (from 17.6.1.2 footnote 7)
(There are alternative forms of some operators - not, and, xor, or - though annoyingly Visual C++ disables them by default to avoid breaking old code that used them but not as operators.)
As Potatoswatter points out in a comment, in many other places the Standard defines lexical tokens identifier and keyword as mutually exclusive tokens in the Grammar:
"There are five kinds of tokens: identifiers, keywords, ..." (2.7 Tokens)
There's also an edge case where the determination's context sensitive:
If a keyword (2.12) or an alternative token (2.6) that satisfies the syntactic requirements of an identifier (2.11) is contained in an attribute-token, it is considered an identifier. (7.6.1. Attribute Syntax and Semantics 2)
Non-keyword identifiers you still shouldn't use
Some identifiers, like "std" or "string", have a specific usage specified in the C++ Standard - they are not keywords though. Generally, the compiler itself doesn't treat them any differently to your own code, and if you don't include any Standard-specified headers then the compiler probably won't even know about the Standard-mandated use of "std". You might be able to create your own function, variable or type called "std". Not a good idea though... while it's nice to understand the general division between keywords and the Standard library, implementations have freedom to blur the boundaries so you should just assume C++ features work when relevant headers are included and your usage matches documentation, and not do anything that might conflict.