I have a simple program that asks for a number and gives the factorial of that number. I used godbolt.org to convert the C++ code to convert it into Assembly. I needed to download a Assembly file, but godbolt does not have an option to. I also found that the assembly is different when comparing them. Here is my code:
#include<iostream>
using namespace std;
int main()
{
int num, i;
int product =1;
cout<<"Enter a number:\n"<< endl;
cin>>num;
for(i=num;i>0; i--)
product = product * i;
cout<<"The factorial for " << num << "is: \n"<< product;
return 1;
}
Assembly code from godbolt.org:
.LC0:
.string "Enter a number:\n"
.LC1:
.string "The factorial for "
.LC2:
.string "is: \n"
main:
push rbp
mov rbp, rsp
sub rsp, 16
mov DWORD PTR [rbp-8], 1
mov esi, OFFSET FLAT:.LC0
mov edi, OFFSET FLAT:_ZSt4cout
call std::basic_ostream<char, std::char_traits<char> >& std::operator<< <std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char const*)
mov esi, OFFSET FLAT:_ZSt4endlIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_
mov rdi, rax
call std::basic_ostream<char, std::char_traits<char> >::operator<<(std::basic_ostream<char, std::char_traits<char> >& (*)(std::basic_ostream<char, std::char_traits<char> >&))
lea rax, [rbp-12]
mov rsi, rax
mov edi, OFFSET FLAT:_ZSt3cin
call std::basic_istream<char, std::char_traits<char> >::operator>>(int&)
mov eax, DWORD PTR [rbp-12]
mov DWORD PTR [rbp-4], eax
jmp .L2
.L3:
mov eax, DWORD PTR [rbp-8]
imul eax, DWORD PTR [rbp-4]
mov DWORD PTR [rbp-8], eax
sub DWORD PTR [rbp-4], 1
.L2:
cmp DWORD PTR [rbp-4], 0
jg .L3
mov esi, OFFSET FLAT:.LC1
mov edi, OFFSET FLAT:_ZSt4cout
call std::basic_ostream<char, std::char_traits<char> >& std::operator<< <std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char const*)
mov rdx, rax
mov eax, DWORD PTR [rbp-12]
mov esi, eax
mov rdi, rdx
call std::basic_ostream<char, std::char_traits<char> >::operator<<(int)
mov esi, OFFSET FLAT:.LC2
mov rdi, rax
call std::basic_ostream<char, std::char_traits<char> >& std::operator<< <std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char const*)
mov rdx, rax
mov eax, DWORD PTR [rbp-8]
mov esi, eax
mov rdi, rdx
call std::basic_ostream<char, std::char_traits<char> >::operator<<(int)
mov eax, 1
leave
ret
Assembly code from Visual Studio: The assembly code from Visual Studio is too long to include in the post.
I thought I could just do it in Visual Studio with the same results. To see the asm file in Visual Studio I right click my source file > properties > C/C++ > Output Files > Assembler Output, and then select "Assembly-Only Listing (/FA)". I then go to my project file and open the asm to see the assembly code. The assembly code in Visual Studio is significantly longer than on godbolt. Am I selecting the wrong file or property option?