C++ syntax: Difference between revisions

Content deleted Content added
Added {{Lead too short}} tag
No edit summary
Line 258:
 
These objects have a dynamic lifespan and can be created directly with a call to {{cpp|new}} and destroyed explicitly with a call to {{cpp|delete}}.<ref name="C++11 3.7.4">[[International Organization for Standardization|ISO]]/[[International Electrotechnical Commission|IEC]]. ''[https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3797.pdf Programming Languages – C++11 Draft (n3797)] {{Webarchive|url=https://web.archive.org/web/20181002093659/http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3797.pdf |date=2 October 2018 }} §3.7.4 Dynamic Storage duration <nowiki>[</nowiki>basic.stc.dynamic<nowiki>]</nowiki>''</ref> C++ also supports <code>malloc</code> and <code>free</code>, from C, but these are not compatible with {{cpp|new}} and {{cpp|delete}}. Use of {{cpp|new}} returns an address to the allocated memory. The C++ Core Guidelines advise against using {{cpp|new}} directly for creating dynamic objects in favor of smart pointers through {{cpp|make_unique<T>}} for single ownership and {{cpp|make_shared<T>}} for reference-counted multiple ownership,<ref>{{Cite web |url=https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#r11-avoid-calling-new-and-delete-explicitly |title=C++ Core Guidelines |website=isocpp.github.io |access-date=2020-02-09 |archive-date=8 February 2020 |archive-url=https://web.archive.org/web/20200208160101/http://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#r11-avoid-calling-new-and-delete-explicitly |url-status=live}}</ref> which were introduced in C++11.
 
== Inline Assembly ==
Programs developed in C or C++ often utilize inline assembly to take advantage of its low-level functionalities, greater speed, and enhanced control compared to high-level programming languages<ref name="Bokil2021">Bokil, Milind A. (2021). "[https://www.researchgate.net/publication/354744729_Writing_Assembly_Routines_within_CC_and_Java_Programs Writing Assembly Routines within C/C++ and Java Programs]". ResearchGate. Retrieved April 1, 2025.</ref><ref name="Vilhena2024">Vilhena, Paulo Emílio de; Lahav, Ori; Vafeiadis, Viktor; Raad, Azalea (2024). "[https://doi.org/10.1145/3689749 Extending the C/C++ Memory Model with Inline Assembly]". Proceedings of the ACM on Programming Languages, Vol. 8, OOPSLA2, Article 309. doi:10.1145/3689749.</ref> when optimizing for performance is essential. C++ provides support for embedding [[Assembly language|assembly]] language using asm declarations<ref name="cppreferenceAsm">cppreference.com contributors. "[https://en.cppreference.com/w/cpp/language/asm asm declaration]". ''cppreference.com''. Retrieved April 1, 2025.</ref>, but the compatibility of [[inline assembly]] varies significantly between [[compilers]] and architectures. Unlike high-level language features such as [[Python (programming language)|Python]] or [[Java (programming language) |Java]], assembly code is highly dependent on the underlying processor and compiler implementation.
 
=== Variations across compilers ===
Different C++ compilers implement inline assembly in distinct ways.
 
*GCC ([[GNU Compiler Collection]]) and [[Clang]] <ref>{{Cite web |title=Extended Asm (Using the GNU Compiler Collection) |url=https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html |website=GCC Online Documentation |publisher=GNU Project |access-date=April 1, 2025}}</ref>: Use the GCC extended inline assembly syntax. Using <syntaxhighlight lang="C++" inline>__asm__</syntaxhighlight> keyword instead of <syntaxhighlight lang="C++" inline>asm</syntaxhighlight> when writing code that can be compiled with <syntaxhighlight lang="C++" inline>-ansi</syntaxhighlight> and <syntaxhighlight lang="C++" inline>-std</syntaxhighlight> options, which allows specifying input/output operands and clobbered registers. This approach is widely adopted, including by Intel<ref name="IntelInlineAssembly">Intel Corporation. "[https://www.intel.com/content/www/us/en/docs/cpp-compiler/developer-guide-reference/2021-9/inline-assembly.html Inline Assembly]". ''Intel® C++ Compiler Classic Developer Guide and Reference'', Version 2021.9. Retrieved April 1, 2025.</ref> and IBM<ref name="IBMInlineAssembly">IBM. "[https://www.ibm.com/docs/en/xl-c-aix/13.1.3?topic=statements-inline-assembly-extension Inline assembly statements (IBM extension)]". ''IBM Documentation''. Retrieved April 1, 2025.</ref> compilers.
 
*MSVC ([[Microsoft Visual C++]]): The inline assembler is built into the compiler. Previously supported inline assembly via the <syntaxhighlight lang="C++" inline>__asm</syntaxhighlight> keyword, but this support has been removed in 64-bit mode, requiring separate .asm modules instead<ref>{{Cite web |title=Inline Assembler Overview |url=https://learn.microsoft.com/en-us/cpp/assembler/inline/inline-assembler-overview?view=msvc-170 |website=Microsoft Learn |publisher=Microsoft |access-date=1 April 2025}}</ref>.
 
*TI ARM Clang and Embedded Compilers <ref>{{Cite web |title=Interfacing C and C++ With Assembly Language |url=https://software-dl.ti.com/codegen/docs/tiarmclang/compiler_tools_user_guide/compiler_manual/runtime_environment/interfacing-c-and-c-with-assembly-language-stdz0544217.html#interfacing-c-and-c-with-assembly-language |website=Texas Instruments |publisher=Texas Instruments Incorporated |date=February 23, 2025 |access-date=April 1, 2025}}</ref>: Some embedded system compilers, like Texas Instruments' TI Arm Clang, allow inline assembly but impose stricter rules to avoid conflicts with register conventions and calling conventions.
 
=== Interoperability between C++ and Assembly ===
C++ provides two primary methods of integrating ASM code.
 
1. Standalone assembly files – Assembly code is written separately and linked with C++ code. <ref>{{cite web |url=https://wiki.osdev.org/C%2B%2B_to_ASM_linkage_in_GCC |title=C++ to ASM linkage in GCC |website=OSDev Wiki |access-date=1 April 2025}}</ref>
 
2. [[Inline assembly]] – Assembly code is embedded within C++ code using compiler-specific extensions.
 
'''Example Code for ASM Compatibility'''
*When calling an assembly function from C++, use <syntaxhighlight lang="C++" inline>extern "C"</syntaxhighlight> to prevent C++ name mangling.
<syntaxhighlight lang="cpp" line="1">
//main.cpp
import std;
 
extern "C" int add_asm(int, int); // Declare the assembly function
 
int main() {
int result = add_asm(5, 7);
std::println("Result from ASM: {}", result);
return 0;
}
</syntaxhighlight>
 
<syntaxhighlight lang="cpp" line="1">
#asm code using RISC-V architecture
.section .text
.global add_asm
 
add_asm:
add a0, a0, a1 # Add first argument (a0) and second argument (a1), store in a0
ret # Return (a0 holds return value)
</syntaxhighlight>
*Global variables in assembly must be declared as <syntaxhighlight lang="C++" inline>extern</syntaxhighlight> in C++ and marked <code>.global</code> in assembly.
<syntaxhighlight lang="cpp" line="1">
// main.cpp
import std;
 
extern "C" int global_var; // Declare global variable from assembly
 
int main() {
std::println("Global variable from ASM: {}", global_var);
return 0;
}
</syntaxhighlight>
<syntaxhighlight lang="cpp" line="1">
#asm using RISC-V architecture
.section .data
.global global_var
.align 4
global_var:
.word 42 # Define integer value
</syntaxhighlight>
 
*Inline assembly allows embedding ASM directly in C++ using the <syntaxhighlight lang="C++" inline>asm</syntaxhighlight> keyword.
<syntaxhighlight lang="cpp" line="1">
//main.cpp (using GCC/CLANG compiler)
import std;
 
int main() {
int x = 10, y = 20, sum;
 
asm volatile (
"add %0, %1, %2"
: "=r" (sum) // Output operand (stored in a register)
: "r" (x), "r" (y) // Input operands (stored in registers)
);
 
std::println("Sum using inline ASM: {}", sum);
return 0;
}
</syntaxhighlight>
 
== Encapsulation ==