What happens here? sizeof(short_int_variable + char_variable)

前端 未结 5 1712
鱼传尺愫
鱼传尺愫 2020-12-03 22:03
#include 
 int main()        
{

           short int i = 20;

            char c = 97;

            printf(\"%d, %d, %d\\n\", sizeof(i), sizeof(c), s         


        
相关标签:
5条回答
  • 2020-12-03 22:46
    1) sizeof(i) ==> sizeof(short int) = 2
    
    2) sizeof(c) ==> sizeof(char) = 1
    
    3) sizeof(c + i [97+20]) ==> sizeof(int) = 4 // result in constant value which is int as default 
    
    0 讨论(0)
  • 2020-12-03 22:55

    Because of C's standard integral promotion rules, the type of the expression c + i is int, so that's why you're getting the equivalent of sizeof (int).

    Note that sizeof is not a function, the parenthesis are only needed when naming a type and to resolve precendence conflicts. Your code coule be written:

    printf("%zu, %zu, %zu\n", sizeof i, sizeof c, sizeof (c + i));
    

    The final use of sizeof has parentheses since sizeof binds tighter than +, saying sizeof c + i would be parsed as (sizeof c) + i which is not the desired result.

    Also note that it's a compile-time construct most of the time, the expression is never actually evaluated. All that happens is that the compiler "pretends" to evaluate it, to figure out the type of the expression, and then gives you the size of a value of that type. The actual value never needs to exist, which is sometimes neat.

    The type of the value returned by sizeof is size_t, which is printed using %zu (it's not int).

    0 讨论(0)
  • 2020-12-03 22:56

    The data type of a is "short int". -32768 ~ +32767

    The data type of c is "char". 0 ~ 255

    When you add a to c it is not either short int nor char, it becomes int!

    Here is is an example code which help you to get the variable data type:

    #include <typeinfo>
    
    int main()
    {
        short int a = 1;
        char c = 'A';
        std::cout << typeid(a + c).name() << std::endl;
    
        return 1;
    }
    
    0 讨论(0)
  • 2020-12-03 23:02

    sizeof only works at compiletime to get the size of an expression.

    The following wont actually increase 'c':

    c = sizeof(++c);

    The expression sizeof(a + b) will return the largest type with unsigned having precedence

    0 讨论(0)
  • 2020-12-03 23:08

    As others have told, sizeof is computed at compile-time.

    Here, value of the expression c + i integer, as c and i are promoted (integral promotion) to int and thus

    sizeof( c + i )
    

    gives you 4 bytes on 32-bit machine..

    0 讨论(0)
提交回复
热议问题