sizeof (char)*

Hi

Please consider the following expressions:

1
2
3
4
5
   int bufsize1;
   int bufsize2 = 80;

   cout << sizeof (char)* bufsize1 << endl;
   cout << sizeof (char)* bufsize2 << endl;


The 1st cout statement gives an O/P of 0.
However, the 2nd cout statement gives an O/P of 80.

Here's what I see is happening here:
1) In the cout statement, an int is cast to a char pointer.
2) Then the sizeof operator is applied to the above result.

However, I don't understand why the 2nd statement results in a char pointer that is 80 bytes long. Why does the cast take into account the value of bufsize2?

Thanks
Steven
Last edited on
It is not a cast but a multiplication. sizeof (char) (usually 1) which is multiplied with the right (int) expression.
Excellent point raised by you.

An alternative is shown below (which I just thought of):

Is what's happening the equivalence between an array and a pointer?

1
2
3
4
5
6
const int bufsize2 = 80;

char ca[bufsize2];

cout << sizeof (char)* bufsize2 << endl;		// 80
cout << sizeof ca << endl;				        // 80 


So which is happening : a multiplication or a cast?

What do the operator precedence rules state in this instance?

Thanks.
Steven
Read this:

http://www.cplusplus.com/doc/tutorial/operators/

sizeof is resolved at compile time (i.e. sizeof (char) is replaced by 1). Hence there is no precedence involved.

There is no cast in your example.
sizeof is resolved at compile time (i.e. sizeof (char) is replaced by 1). Hence there is no precedence involved.
Since sizeof is an operator, it does have precedence. It's precedence and associativity are the same as those of prefix increment.

http://cs.smu.ca/~porter/csc/ref/cpp_operators.html
Topic archived. No new replies allowed.