C++ syntax: Difference between revisions

Content deleted Content added
No edit summary
Tags: Mobile edit Mobile web edit
 
(20 intermediate revisions by 6 users not shown)
Line 38:
* <code>alignas</code>
* <code>alignof</code>
* <code>and</code>
* <code>and_eq</code>
* <code>asm</code>
* <code>auto</code>
* <code>bitand</code>
* <code>bitor</code>
* <code>bool</code>
* <code>break</code>
Line 53 ⟶ 49:
* <code>char32_t</code>
* <code>class</code>
* <code>compl</code>
* <code>concept</code>
* <code>const</code>
Line 90 ⟶ 85:
* <code>new</code>
* <code>noexcept</code>
* <code>not</code>
* <code>not_eq</code>
* <code>nullptr</code>
* <code>operator</code>
* <code>or</code>
* <code>or_eq</code>
* <code>private</code>
* <code>protected</code>
Line 128 ⟶ 119:
* <code>wchar_t</code>
* <code>while</code>
{{div col end}}
 
The keyword [[restrict|<code>restrict</code>]], though present in C, is not standard in C++, though some compilers may support it. The keyword <code>fortran</code>, a conditionally supported keyword in C which denotes linkage for the [[Fortran]] programming language, is conditionally supported in C++.
 
=== Alternative operator keywords ===
The following words are reserved keywords, but are used as alternative spellings for operators and tokens that use non-ISO646 characters.
{{div col|colwidth=15em}}
* <code>and</code>
* <code>and_eq</code>
* <code>bitand</code>
* <code>bitor</code>
* <code>compl</code>
* <code>not</code>
* <code>not_eq</code>
* <code>or</code>
* <code>or_eq</code>
* <code>xor</code>
* <code>xor_eq</code>
Line 167 ⟶ 174:
* <code>#__has_embed</code>
{{div col end}}
 
The following macros are often ubiquitously used in C and thus C++ as well:
* <code>NULL</code> (expands to <code>(void*)0</code>, used prior to the introduction of <code>nullptr</code> to represent a null pointer)
* <code>NDEBUG</code> (a macro meaning "no-debug", used primarily to control whether <code>assert()</code> calls are ignored)
* <code>assert()</code> (a macro with arguments, which terminates the program if the argument evaluates to <code>false</code>, <code>0</code>, or <code>nullptr</code>, and can be disabled by <code>NDEBUG</code>)
 
=== Code blocks ===
Line 233 ⟶ 245:
int main(int argc, char* argv[]) {
std::println("argc = {}", argc);
for (size_t i = 0; i < argc; ++i) {
std::println("argv[{}] = {}", i, argv[i]);
}
}
</syntaxhighlight>
Line 546 ⟶ 559:
 
=== Modules ===
{{main|Modules (C++)}}
{{excerpt|Precompiled header|Modules}}
Modules do not use the C preprocessor at all, and are instead handled directly by the compiler.<ref name=cppreferencemodules /> A module is declared using <code>export module</code>, and the beginning of the module preamble begins with <code>module;</code>. Exported symbols which will be made accessible to importing translation units are marked <code>export</code>, and a module is imported into the translation unit using <code>import</code>. Modules do not export macros, due to being handled after the preprocessing step.
 
Modules may also have partitions, which cannot be imported individually but are owned by a larger module.
 
==== Example ====
{{excerpt|Modules (C++)|Example}}
A simple example of using C++ modules is as follows:
 
== Attributes ==
{{mono|MyClass.cppm}}
Since C++11, C++ has supported attribute specifier sequences.<ref>{{cite web|title=Attribute specifier sequence (since C++11)|url=https://cppreference.com/w/cpp/language/attributes.html|website=cppreference.com|access-date=6 June 2025}}</ref> Attributes can be applied to any symbol that supports them, including classes, functions/methods, and variables, and any symbol marked with an attribute will be specifically treated by the compiler as necessary. These can be thought of as similar to [[Java annotation]]s for providing additional information to the compiler, however they differ in that attributes in C++ are not metadata that is meant to be accessed using reflection. C++26 adds support for annotations for reflection. Furthermore, one cannot create custom attributes in C++, unlike in Java where one may define custom annotations in addition to the standard ones. However, C++ does have implementation/vendor-specific attributes which are non-standard. These typically have a namespace associated with them. For instance, GCC and Clang have attributes under the <code>gnu::</code> namespace, and all such attributes are of the form {{cpp|[[gnu::*]]}}.
<syntaxhighlight lang="cpp">
export module myproject.MyClass;
 
One may apply multiple attributes as a list, for instance {{cpp|[[A, B, C]]}} (where <code>A</code>, <code>B</code>, and <code>C</code> are attributes). Furthermore, attributes may also accept arguments, like {{cpp|[[A("This is a parameter")]]}}. The following is an example of using some attributes in C++.
import std;
 
<syntaxhighlight lang="cpp">
using String = std::string;
class MyObject {
 
private:
export namespace myproject {
[[no_unique_address]]
class MyClass {
private:int x;
public:
int x;
[[nodiscard]]
String name;
bool satisfiesProperty() const noexcept {
public:
MyClassif (int[[likely]] x, const> String& name0): {
x{x},return name{name} {}true;
 
int getX() const noexcept {
return x;
}
return false;
 
}
void setX(int newX) noexcept {
};
x = newX;
};
 
String getName() const noexcept {
return name;
}
 
void setName(const String& newName) noexcept {
name = newName;
}
};
}
</syntaxhighlight>
 
{{mono|Main.cpp}}
<syntaxhighlight lang="cpp">
import std;
 
import myproject.MyClass;
 
using myproject::MyClass;
 
int main() {
MyClass me(10, "MyName");
me.setX(15);
 
std::println("Hello, {}!", me);
}
</syntaxhighlight>
 
== Attributes ==
Since C++11, C++ has supported attribute specifier sequences<ref>{{cite web|title=Attribute specifier sequence (since C++11)|url=https://cppreference.com/w/cpp/language/attributes.html|website=cppreference.com|access-date=6 June 2025}}</ref>. Attributes can be applied to any symbol that supports them, including classes, functions/methods, and variables, and any symbol marked with an attribute will be specifically treated by the compiler as necessary. These can be thought of as similar to [[Java annotation]]s for providing additional information to the compiler, however they differ in that attributes in C++ are not metadata that is meant to be accessed using reflection. Furthermore, one cannot create custom attributes in C++, unlike in Java where one may define custom annotations in addition to the standard ones. However, C++ does have implementation/vendor-specific attributes which are non-standard. These typically have a namespace associated with them. For instance, GCC and Clang have attributes under the <code>gnu::</code> namespace, and all such attributes are of the form {{cpp|[[gnu::*]]}}.
 
One may apply multiple attributes as a list, for instance {{cpp|[[A, B, C]]}} (where <code>A</code>, <code>B</code>, and <code>C</code> are attributes). Furthermore, attributes may also accept arguments, like {{cpp|[[A("This is a parameter")]]}}.
 
=== Standard attributes ===
Line 667 ⟶ 647:
[[using gnu : const, always_inline, hot]] [[nodiscard]]
int f[[gnu::always_inline]](); // an attribute may appear in multiple specifiers
</syntaxhighlight>
 
== Reflection ==
In addition to basic metaprogramming provided in header <code><type_traits></code>, [[C++26]] introduces compile-time reflection. Compile-time reflection capabilities can be accessed in header <code><meta></code> and declarations are stored in namespace <code>std::meta</code>.
 
=== Annotations ===
Most declarations can have annotations attached, which are just values associated with that declaration. Like [[Java annotation]]s, annotations can be accessed using reflection. Annotations are different from attributes as attributes are primarily a means to communicate information to the compiler, while annotations are a feature of reflection and allow arbitrary constants and metadata to be attached, making them customisable to programs, unlike attributes. This allows for bridging the communication between the library API and the user.
<syntaxhighlight lang="cpp">
using custom::Debug;
using custom::EnumFlag;
using custom::Rename;
 
enum class [[=EnumFlag]] Toggle: uint8_t {
Off,
On
};
 
struct [[=Debug]] Person {
[[=Rename("full name")]]
std::string fullName;
int age;
};
</syntaxhighlight>
 
The annotations have no initial meaning unless some implementations use those annotations to identify some characteristics and features.
 
Creating an annotation to generate a specialisation for <code>std::formatter<T></code> is as follows:
<syntaxhighlight lang="cpp">
template <auto V>
struct Derived {};
 
template <auto V>
inline constexpr Derived<V> Derive;
 
inline constexpr struct {} Debug;
 
template <typename T>
requires (std::meta::has_annotation(^^T, Derive<Debug>))
struct std::formatter<T> {
// ...
};
 
struct [[=Derive<Debug>]] Point {
int x;
int y;
};
 
int main() {
Point p = Point { .x = 1, .y = 2 };
// prints p = Point { .x = 1, .y = 2 }
std::println("p = {}", p);
}
</syntaxhighlight>
 
== See also ==
* [[C++ standard library]]
* [[C syntax]]
* [[Java syntax]]
* [[C Sharp syntax|C# syntax]]
* [[Rust syntax]]
 
== Notes ==