Skip to content

Instantly share code, notes, and snippets.

@dmazary
Created January 20, 2012 17:12
Show Gist options
  • Save dmazary/1648498 to your computer and use it in GitHub Desktop.
Save dmazary/1648498 to your computer and use it in GitHub Desktop.
C ternary operator hack
gcc -S -O2 ternary.c -o ternary.s
gcc -S -O2 ifelse.c -o ifelse.s
#include <stdio.h>
#include <stdlib.h>
void fn(int c) {
int x = 0, y = 0, v = 7;
if (c) {
x = v;
} else {
y = v;
}
printf("x: %d\ty: %d\n", x, y);
}
int main(int argc, char* argv[]) {
if (argc != 2)
return -1;
fn(atoi(argv[1]));
return 0;
}
.file "ifelse.c"
.section .rodata.str1.1,"aMS",@progbits,1
.LC0:
.string "x: %d\ty: %d\n"
.text
.p2align 4,,15
.globl fn
.type fn, @function
fn:
.LFB34:
.cfi_startproc
cmpl $1, %edi
movl $.LC0, %esi
sbbl %ecx, %ecx
andl $7, %ecx
cmpl $1, %edi
movl $1, %edi
sbbl %edx, %edx
xorl %eax, %eax
notl %edx
andl $7, %edx
jmp __printf_chk
.cfi_endproc
.LFE34:
.size fn, .-fn
.section .text.startup,"ax",@progbits
.p2align 4,,15
.globl main
.type main, @function
main:
.LFB35:
.cfi_startproc
subq $8, %rsp
.cfi_def_cfa_offset 16
cmpl $2, %edi
movl $-1, %eax
jne .L5
movq 8(%rsi), %rdi
movl $10, %edx
xorl %esi, %esi
call strtol
movl %eax, %edi
call fn
xorl %eax, %eax
.L5:
addq $8, %rsp
.cfi_def_cfa_offset 8
ret
.cfi_endproc
.LFE35:
.size main, .-main
.ident "GCC: (Ubuntu/Linaro 4.6.2-10ubuntu1) 4.6.2"
.section .note.GNU-stack,"",@progbits
#include <stdio.h>
#include <stdlib.h>
void fn(int c) {
int x = 0, y = 0, v = 7;
*(c ? &x : &y) = v;
printf("x: %d\ty: %d\n", x, y);
}
int main(int argc, char* argv[]) {
if (argc != 2)
return -1;
fn(atoi(argv[1]));
return 0;
}
.file "ternary.c"
.section .rodata.str1.1,"aMS",@progbits,1
.LC0:
.string "x: %d\ty: %d\n"
.text
.p2align 4,,15
.globl fn
.type fn, @function
fn:
.LFB34:
.cfi_startproc
leaq -12(%rsp), %rdx
leaq -16(%rsp), %rax
testl %edi, %edi
movl $0, -16(%rsp)
movl $0, -12(%rsp)
movl $.LC0, %esi
cmove %rdx, %rax
movl $1, %edi
movl $7, (%rax)
movl -12(%rsp), %ecx
xorl %eax, %eax
movl -16(%rsp), %edx
jmp __printf_chk
.cfi_endproc
.LFE34:
.size fn, .-fn
.section .text.startup,"ax",@progbits
.p2align 4,,15
.globl main
.type main, @function
main:
.LFB35:
.cfi_startproc
subq $8, %rsp
.cfi_def_cfa_offset 16
cmpl $2, %edi
movl $-1, %eax
jne .L5
movq 8(%rsi), %rdi
movl $10, %edx
xorl %esi, %esi
call strtol
movl %eax, %edi
call fn
xorl %eax, %eax
.L5:
addq $8, %rsp
.cfi_def_cfa_offset 8
ret
.cfi_endproc
.LFE35:
.size main, .-main
.ident "GCC: (Ubuntu/Linaro 4.6.2-10ubuntu1) 4.6.2"
.section .note.GNU-stack,"",@progbits
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment