user1064913
user1064913

Reputation: 323

Introduction to Data Types

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

Answers (6)

fge
fge

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

Tom van der Woerdt
Tom van der Woerdt

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 chars, 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 chars, and defined with double quotes. A single char is defined with single quotes.

Upvotes: 0

Bryan C.
Bryan C.

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

Andrew Marshall
Andrew Marshall

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

Andre
Andre

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

Mysticial
Mysticial

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

Related Questions