3

What is the output of these program?

Actually it show 2byte but I didn't get that how it calculates 2byte?

Comments
  • 4
    Well, each char is 1 byte, and you asked it to calculate the size of two chars
  • 5
    Coding in notepad. WHAHDHSIHHFOFBXXJXI
  • 0
    @TheBardAbaddon as per your answer it needs to show 1byte,1byte,1byte... Total 5bytes

    But in actual it shows output as 2byte.🤔🤔 Plz explain?
  • 2
    @filthyranter actually For clear visibility , I was uploaded photo of notepad program...
  • 4
    So I'm assuming you're in c.

    What you're asking is what is the size of the return value of the operation char+char. My guess is that the compiler is promoting types as the addition can be done faster in a type of length 2 than 1.

    When I run equivalent code I get 4 returned so it appears to be compiler dependant.
  • 0
    @alwaysmpe just assume there is no returns statement in above program , then also it show same output for "" size of(a+b+c+d+e); ""
  • 0
    @alwaysmpe I just want to know that if i write "sizeof(a)" then I got output as 1 but when I write "sizeof(a+a)" then it shows output as 2 Why?
  • 6
    @pranit16 there is a difference between sizeof(a+b+c) and sizeof(a) + sizeof(b) + sizeof(c).

    The second is "what is the size of all of these variables summed together".
    The first, in your code, is "what is the size of the value returned by the function char + char".

    There are 2 possible reasons for you seeing the value 2:
    1. Char is of size 2 (c spec requires it to be AT LEAST 1 byte)
    2. The compiler for the addition operation has promoted the types of a, b, c and d to short because it is faster. This is also legal.
  • 2
    @pranit16 put simply you are seeing 2 because the type returned by the addition function is of size 2
  • 1
    For some more information on this read the following:
    http://idryman.org/blog/2012/...
    And
    https://securecoding.cert.org/confl...
  • 0
    @alwaysmpe thanks
  • 3
    Because although a and a are each of type char, the expression a + a is of type int. So is a + b + c + d + e. Anytime you do math with char types, they are converted to int before doing the actual calculations.
  • 0
    @alwaysmpe thank you
Add Comment