-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathadd_arr.c
More file actions
61 lines (50 loc) · 1.24 KB
/
Copy pathadd_arr.c
File metadata and controls
61 lines (50 loc) · 1.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/*
auther: Naman Tamrakar
date: 2023-07-19
description: A sample program to show how you can write a function implementation in assembly
which takes an array and return its sum. `Sum_C` is c implementation of this function, its curresponding
assembly instruction in explained how an instruction in c can be written in assembly.
*/
#include <stdio.h>
#include <stdlib.h>
int sum_C(int *a, int n) {
int s = 0;
int i = 0;
while (i < n) {
s += a[i];
i++;
}
return s;
}
__attribute__((naked))
int sum(int *a, int n) {
__asm__(
// s = 0
"movl $0, %eax;"
// i = 0
"movl $0, %ecx;"
"loop:;"
// if i == n then jump to end
"cmpl %esi, %ecx;"
"je end;"
// s += a[i]
"addl (%rdi, %rcx, 4), %eax;"
// i++
"incl %ecx;"
// jump to loop start
"jmp loop;"
"end:"
// when done return as result already saved in %eax register
"ret;"
);
}
int main() {
int n;
scanf("%d", &n);
int *arr = malloc(sizeof(int) * n);
for (int i=0; i<n; i++)
scanf("%d", &arr[i]);
printf("%d", sum(arr, n));
free(arr);
return 0;
}