Jump to content

sizeof operator confusion..

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
1 reply to this topic

#1
novice

novice

    Newbie

  • Members
  • PipPip
  • 13 posts
hello guys, i have a small confusion with regards to the sizeof operator..

I tried out this code as a C program {some filename.c} and the output observed was 1, 4

#include<stdio.h>

int main()

{

    char ch='A';

    printf("%d%d",sizeof(ch),sizeof('A'));

       

}

then i tried the same code as a C++ program {some filename.cpp}
{no other changes made... all i did was File --> Save As --> filename.cpp}

and to my surprise, the output was 1,1.

does this mean that C and C++ have different ways of handling sizeof operator ??

please clarify.

PS : i use Dev CPP on Windows XP.

#2
CPD

CPD

    Learning Programmer

  • Members
  • PipPipPip
  • 57 posts
It's not the sizeof operator, it's how C and C++ determine the size for character constants. In C a character constant has a type of int, and because that causes problems with C++'s enhanced static type checking, the type of a character constant was changed to char.

This is one of the places where C and C++ differ, but your results are expected and normal.