What happens here? sizeof(short_int_variable + char_variable)

自作多情 提交于 2019-11-28 01:04:25

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).

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 

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..

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

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;
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!