The output is not exactly I want.
But if I set another array, it works.
int n1, n2;
char str[9];
n1 = s_b(argv[1]);
n2 = s_b(argv[2]);
printf(" %s %s\n", argv[1], argv[2]);
printf("~ : %s %s \n", b_s(str, ~n1), b_s(str, ~n2));
int s_b(char *p)
{
int n = 0;
int index = 0;
while (p[index] != '\0')
{
n <<= 1;
n |= (p[index++] - '0');
}
return n;
}
char *b_s(char *p, int n)
{
int ind;
for (ind = 7; ind >= 0; ind--)
{
p[ind] = (n & 1) + '0';
n >>= 1;
}
p[8] = '\0';
return p;
}
s_b(char *)
means string to binary
b_s(char *, int)
means binary to string stored in char *
For example:
Input:
FILENAME 11101110 00010001
Output:
11101110 00010001
00010001 00010001
But what I expected was:
Output:
11101110 00010001
00010001 11101110
In answer to the question in your title, the order of evaluations of function arguments (for printf
and every other function) is unspecified. That means you can't depend on it. But it turns out that's not your problem here. (Or see more on this question below.)
The real problem is that you're using one array str
to hold the results of the two calls to b_s
, so the second call (whichever one it is) overwrites the first. So printf
ends up printing two copies of the same thing.
You can fix this in either of two ways.
1. Use two arrays:
char str1[9], str2[9];
printf("~ : %s %s \n", b_s(str1,~n1), b_s(str2,~n2));
(Perhaps you had discovered this solution already.)
2. Change it to
printf("~ : %s ", b_s(str, ~n1));
printf("%s \n", b_s(str, ~n2));
Now you print each string as it's created, before the second call to b_s()
overwrites it.
Addendum: I may have misunderstood your question "What the order of evaluation of function in printf?". When you call printf("%d %d\n", a(), b())
, it is unspecified whether a()
gets called first or b()
gets called first. But it's guaranteed that both a()
and b()
will get called before printf
is called. Similarly, in your call printf("%s %s\n", b_s(...), b_s(...))
, both calls to b_s()
happen before printf
gets called. That's why the second call to b_s
overwrites the string created by the first call, such that the same string is printed twice.