Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I get different results when I apply sizeof operator?

Tags:

I have this program

#include <stdio.h>
int main()
{
   char arr[100];
   printf("%d", (int)sizeof(0,arr));
}

This prints 4 when compiled as a C file and prints 100 as a C++ file. Why? I am using gcc.

like image 221
user724619 Avatar asked Apr 23 '11 19:04

user724619


People also ask

What is the output of sizeof operator?

The sizeof operator applied to a type name yields the amount of memory that can be used by an object of that type, including any internal or trailing padding. The result is the total number of bytes in the array. For example, in an array with 10 elements, the size is equal to 10 times the size of a single element.

Why is sizeof () an operator and not a function?

sizeof operator is compile time entity not runtime and don't need parenthesis like a function. When code is compiled then it replace the value with the size of that variable at compile time but in function after function gets execute then we will know the returning value.

How does sizeof operator work in C++?

The sizeof is a keyword, but it is a compile-time operator that determines the size, in bytes, of a variable or data type. The sizeof operator can be used to get the size of classes, structures, unions and any other user defined data type.

What does sizeof array return?

The sizeof() operator returns pointer size instead of array size. The 'sizeof' operator returns size of a pointer, not of an array, when the array was passed by value to a function. In this code, the A object is an array and the sizeof(A) expression will return value 100. The B object is simply a pointer.


1 Answers

In C the result of the right hand operand of the comma operator has a type and value. In C a comma operator does not yield an lvalue. So there is an lvalue to rvalue conversion resulting in decay of array type to pointer type. So in C what you get is the result of sizeof(char*).

In C++ the result of a comma expression is an lvalue. There is no such conversion[as in C] and what you get is the sizeof(arr) i.e 100

like image 56
Prasoon Saurav Avatar answered Oct 23 '22 04:10

Prasoon Saurav