Code:int main() { int a=7, t=0; t=--a+--a+a+++a; printf("%d",t); }
output: 20
I could not understand why it prints '20' ? please explain it !
Code:int main() { int a=7, t=0; t=--a+--a+a+++a; printf("%d",t); }
output: 20
I could not understand why it prints '20' ? please explain it !
Read this FAQ series on expressions in C. Basically, you are looking at the results of undefined behaviour.
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
This is the assembly instruction flow for the given program. You can see the execution flow.Code:.file "cpb19.c" .section .rodata .LC0: .string "%d" .text .globl main .type main, @function main: leal 4(%esp), %ecx andl $-16, %esp pushl -4(%ecx) pushl %ebp movl %esp, %ebp pushl %ecx subl $36, %esp movl $7, -8(%ebp) movl $0, -12(%ebp) subl $1, -8(%ebp) <<<<--- '--a' now 'a' is 6 subl $1, -8(%ebp) <<<<--- '--a' now 'a' is 5 movl -8(%ebp), %eax addl -8(%ebp), %eax <<<<--- adding '--a+--a' 5+5=10 addl -8(%ebp), %eax <<<<--- adding 10+5 addl -8(%ebp), %eax <<<<--- adding 15+5 movl %eax, -12(%ebp) addl $1, -8(%ebp) movl -12(%ebp), %eax movl %eax, 4(%esp) movl $.LC0, (%esp) call printf addl $36, %esp popl %ecx popl %ebp leal -4(%ecx), %esp ret .size main, .-main .ident "GCC: (GNU) 4.2.4 (Ubuntu 4.2.4-1ubuntu4)" .section .note.GNU-stack,"",@progbits
The same answers as you got over here -> Simple c program-please explain output. - Dev Shed
If you'd bothered to read my post, and realised that different compilers give different answers, you would soon realise that the code is broken and the question is meaningless.
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
Welcome to the forum, but please don't get fascinated with this kind of useless code. It is not just non-compliant C, but violates the principle that code should be understandable, as well.
(Exception: obfuscation contests, which are mad fun, and never meant to be understood).
> This is the assembly instruction flow for the given program. You can see the execution flow.
That's the assembly output for your compiler. Undefined Behavior can produce different results depending on what compiler you use.
thanks to laserlight, sana.iitkgp, Salem, Adak, memcpy