tags:

views:

124

answers:

3

I got the most simple code to display sizeof() of a datatype, say an int.

#include <stdio.h>
int main() { 
  printf('%i', sizeof(int));
}

No matter what I do, such as put sizeof(int) into an integer, or use 'zu' instead of 'i', it hands me this error:

error: invalid conversion from ‘int’ to ‘const char*’

Is there something wrong with my compiler? I do not get why I cannot print such a simple sizeof..

EDIT: It seems a printf('%s', 'foo'); STILL tells me I am converting int to const char*, how on earth??

+6  A: 

Try print("%i", sizeof(int));

double quotes is missing

Also explore if you can use cstdio instead of stdio.h if you are on C++.

Chubsdad
Thank you, I had been coding in PHP for too long.. I keep forgetting single quotes aren't for strings.. Grrr.
John
@John: Look at @Richard Cook response. It goes to explain why you got the error. That's a great opportunity to learn!.
Chubsdad
Fix the type or cast the result of `sizeof` to `int`. Otherwise your code will break on 64bit targets.
R..
@R: Agree. Good point
Chubsdad
+5  A: 

Single quotes ' are used to delimit character literals (type int in C) while double quotes " are used to delimit string literals (type "array of char" in C).

printf is declared as follows:

int printf (const char * format, ...)

Thus you are attempting to pass an int where the function expects a const char * or something that can be converted to const char *.

Note: In C++ character literals are type char, string literals are "array of const char".

Richard Cook
Appreciate explaining the reason as well: + 1
Chubsdad
+1  A: 

It should be:

printf("%i\n", sizeof(int));

It should be the double quotes.

antonio081014
No, it should be `printf("%zu\n", sizeof(int));` or `printf("%u\n", (unsigned)sizeof(int));``You're passing the wrong type of argument and the code will break on 64-bit targets.
R..
But it will only give you a warning there.It will cast automatically.
antonio081014
Warning a.k.a error (99.99% of the times), automatically (is the remaing 0.01 %)
Chubsdad
@antonio081014: No, it *cannot* cast it automatically since it is an argument in a variable-argument-list. Variable argument lists are necessarily unprototyped; an `int` is always passed as an `int`, even if the `printf()` function is expecting something else.
caf
More significantly, `size_t` != `int` in general, and there is no guarantee that `sizeof(size_t) == sizeof(int)`, especially in the 64-bit (non-Windows) world. On little-endian (Intel) machines, you may get away with, more by accident than design; on big-endian machines (SPARC, PPC), you will not get away with it - you will typically print zeroes when there is one value, and garbage in subsequent values.
Jonathan Leffler