Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

printf and ++ operator [duplicate]

Tags:

c

#include<stdio.h>
main()
{
    int a=10;
    printf("\n %d %d", a, a++); //11 10
    a=10;
    printf("\n %d %d", a++, a); //10 11
    a=10;
    printf("\n %d %d %d ", a, a++,++a); //12 11 12
}

after running this I got the output given in comments. as far as I know first output is expected because execution of printf goes from right to left but could not understand second and third

like image 914
shrikant Avatar asked Apr 21 '26 11:04

shrikant


1 Answers

Nothing goes "from right to left" in function argument evaluation. When function arguments are evaluated, the order of evaluation is unspecified and there are no sequence points between evaluating separate arguments. This means that there's absolutely no temporal ordering in this process. The arguments can be evaluated in any order, and the process of their evaluation can be intertwined in any way.

However, your code suffers from even worse problems. All three statements that call printf produce undefined behavior (UB) because they either make an attempt to modify the same object (a) twice without a sequence point between the modifications (the third call), or they attempt to modify an object and read it for an independent purpose (the first and the second call). So, it is too early to even mention the order of evaluation. Your code's behavior is undefined.

like image 107
AnT Avatar answered Apr 23 '26 00:04

AnT



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!