+ 15

Why it returns 4

In this statement printf("%d\n",sizeof((b == 1) ? c : b)); b is short integer initialized to 2 c is a float b does not equal to 1 so it should printf sizeof(b) consequently it prints 2 but actually it prints 4 if I switch between b and c >>> b:c it also return 4 Thanks for helping

22nd Jan 2019, 12:35 PM
ABADA S
ABADA S - avatar
11 ответов
+ 9
Thanks for all you are the best
22nd Jan 2019, 6:42 PM
ABADA S
ABADA S - avatar
+ 3
Sahil Bhakat I know that, and the question is why the output is 4 instead of 2 here. We can't just agree that C is wrong?
22nd Jan 2019, 1:51 PM
Anna
Anna - avatar
+ 3
‎‏‪ABADA S‬‏‎ As clarified in the article posted by Zen , the sizeof operator will return the size of the expression, which is the common type that can be used for all possible results. In this case, a 2 byte short can fit into a 4 byte float, but not the other way around. Therefore, the sizeof operator will evaluate for the larger type size in this expression.
22nd Jan 2019, 6:37 PM
David Carroll
David Carroll - avatar
+ 2
Anna you were right from this first see this https://www.sololearn.com/post/61449/?ref=app
23rd Jan 2019, 7:09 AM
Sahil Bhakat
Sahil Bhakat - avatar
+ 2
Anna That is interesting because when I ran this earlier, my code returned a 4. When I used your modified print format, I got 0.00000. This is probably due to different compilers on our systems.
23rd Jan 2019, 7:51 AM
David Carroll
David Carroll - avatar
+ 2
Sahil Bhakat You must have deleted an earlier response because the continuity is now a bit off. Without more context, I'm not sure what the relevance of this article is. Also, why not just paste a link to the page instead of a link to your activity post which is a screenshot of the page?
23rd Jan 2019, 7:55 AM
David Carroll
David Carroll - avatar
+ 1
I'm not sure, but it looks like b is converted to a float in the process. Because if I replace the line with printf("%d\n", (b == 1) ? c : b), my compiler complains that "%d" expects an integer, but the argument has the type float. And when I change it to printf("%.2f\n", (b == 1) ? c : b), the output is 2.00.
22nd Jan 2019, 1:29 PM
Anna
Anna - avatar
+ 1
I thought it should be better to look at and easier than finding the answer of this question as the question i was seaching for is not the same And now i have also mentioned the link in my post
23rd Jan 2019, 7:58 AM
Sahil Bhakat
Sahil Bhakat - avatar
+ 1
Sahil Bhakat You can use the Share link next to the answer in Stackoverflow.com you'd like to highlight to make it clear which response to focus on. Like this: https://stackoverflow.com/a/8535301
23rd Jan 2019, 8:06 AM
David Carroll
David Carroll - avatar
+ 1
David Carrol Yeah i know how to do it and I have done before also but i thought the content was a bit messed up so that's why i did it
23rd Jan 2019, 8:09 AM
Sahil Bhakat
Sahil Bhakat - avatar