Reputation: 323
I just started learning C and copied this directly from a book. Can someone tell me why this doesn't work?
#include <stdio.h>
int main (void)
{
int integerVar = 100;
float floatingVar = 331.79;
double doubleVar = 8.44e+11;
char charVar = "W";
_Bool boolVar = 0;
printf ("integerVar = %i\n", integerVar);
printf ("floatingVar = %f\n", floatingVar);
printf ("doubleVar = %e\n", doubleVar);
printf ("doubleVar = %g\n", doubleVar);
printf ("charVar = %c\n", charVar);
printf ("boolVar = %i\n", boolVar);
return 0;
}
I get this error:
datatypes.c: In function ‘main’:
datatypes.c:8: warning: initialization makes integer from pointer without a cast
Upvotes: 3
Views: 354
Reputation: 121740
"W"
is not a char but a string constant. What you want is 'W'
.
And a string constant is a pointer to a chararacter array (in this case, { 'W', 0 }
), hence the warning: "initialization makes integer from pointer without a cast".
Here, "integer" is meant to be understood as any integer type (char, short, int, long, long long for compilers defining it, and their unsigned variants, and their numerous typedefs...)
Upvotes: 3
Reputation: 29985
In C, there's a difference between strings and chars. In fact, strings are sequences of characters, defined as char[length]
or even char*
(variable length). Because it's multiple char
s, it requires a "pointer" (don't worry, I won't explain).
For the C compiler to know the difference between a char and a string it invented two styles of quotes: single and double quotes. A char
uses a single quotes ('W'
) and a string uses double quotes ("W"
).
You can declare a string like this :
char* myString = "this is a string";
While a single char is declared like this :
char charVar = 'W';
Bottom line: a string is a sequence of char
s, and defined with double quotes. A single char is defined with single quotes.
Upvotes: 0
Reputation: 347
The line char charVar="W";
is not correct in this example because "W" is a string and is being treated as a pointer to an array of characters. Change this to 'W'
to make this a character.
Upvotes: 1
Reputation: 96954
"W"
represents a char*
, or C-string.
'W'
represents a char
, or a single, 1-byte character, and is what you want.
The single/double quotes are what distinguishes the two.
Upvotes: 2
Reputation: 1607
It should be 'w'
not "w"
. The latter one is a zero-terminated string, i.e. it's a pointer to a char array.
Upvotes: 3
Reputation: 471279
The problem here:
char charVar = "W";
you probably meant:
char charVar = 'W';
"W"
is a string. 'W'
is a char. The latter is what you want.
Upvotes: 6