You are here:

C/issue with sizeof()

Advertisement


Question
QUESTION: Hi Premnath,

int main()
{
int x;
for(x = -1; x< sizeof(int);x++)
  printf("hello\n");
return 0;
}
why i am not getting o/p...let me know the issue.

Thanks in advance
Bhupal.

ANSWER: Hi Dear Bhupal ,

I Don't find any issue with this code .. Lemme know whats the compiler you have tested the code ??
if its a DOS Based compiler sizeOf(int) will return 2 or if its a 32 bit compiler it will return 4  so your output may vary . but there is no chance of missing the output , i have tested this code as well .

Please get back to me. If this is n't help you , Lemme know your problem little clear .

Thanks and Regards
Prince M. Premnath


---------- FOLLOW-UP ----------

QUESTION: Hi Premnath,

         I have tested the scenario on visual studio. for loop condition is failing, so o/p is not displayed. i want to know why codition returning false...

Thanks
Bhupal.

Answer
Hi Dear Bhupal ,


Actually the return type of sizeof operator is unsigned int , where as -1 ( value of x= -1) is a signed integer, the ranges of signed and unsigned ints are different, and when they are compared to one another, the results can be surprising. If you have to make such a comparison, you should explicitly cast one of the values to be compatible with the other, perhaps after checking to ensure that the value you are casting is valid

So i recommend you to use a cast operator , your code will work good

int main()
{
int x;
for(x = -1; x< (int) sizeof(int);x++)
printf("hello\n");
getch();
return 0;
}

I Have tested the above code in Visual Studio , Works fine , Let me know if you still have problems

Thanks And Regards
Prince M. Premnath  

C

All Answers


Answers by Expert:


Ask Experts

Volunteer


Prince M. Premnath

Expertise


I'm sure that I can solve any doubts in Turbo C ,Graphics Programing ,Mouse, Hardware Programming ,File System ,Interrupts, BIOS handling , TSR Programming , General Concepts in C Language, handling inline Assembly statements

Experience

Research over 6+ Years

Organizations
CG-VAK Softwares and Exports Limited

Education/Credentials
Masters in Computer Applications

©2012 About.com, a part of The New York Times Company. All rights reserved.