views:

213

answers:

5

Came across this example in the book im reading and it didn't make sense at all to me, I'm probably missing something but it seems like youre assigning count with the values '10' and then the value 'x' which isnt even an int. Just wondering if this is a syntax that is valid.

The book says this:

The variables count and x are declared to be integer variables in the normal fashion. On the next line, the variable intPtr is declared to be of type “pointer to int.” Note that the two lines of declarations could have been combined into a single line:

int count = 10, x, *intPtr;

here's the program its taken from:

#import <Foundation/Foundation.h>
int main (int argc, char *argv[ ])
{
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    int count = 10, x;

    int *intPtr;

    intPtr = &count;

    x = *intPtr;

    NSLog (@"count = %i, x = %i", count, x);

    [pool drain];

    return 0;

}
+3  A: 

It's equivilent to

int count = 10;
int x;
int *intPtr;
Martin
is it just me or does this seem out of step with some of the syntax laid out in general for c?
nickthedude
It's just you. Initialized declarators are not the same as assignment expressions, and commas between declarators are not treated the same as commas between expressions.
John Bode
Yup, it's just you.
Stephen Canon
A: 

Comma means, that x is also an int, and *intPtr is also int (and intPtr is pointer to int). Its like:

Aunts Mary, Jane, Daryl;
Mary is stupid;
Jane is Old;
Daryl is same as Mary;
alemjerus
As clear as mud
James Morris
+13  A: 

This is just a declaration. Declaration consists of the initial part (declaration specifier) that describes the "basic" part of the type, and a comma-separated sequence of declarators, each of which declares a separate name and, possibly, modifies the basic type. In C you can declare multiple names using the same declaration specifier

int count, x, *intptr;

is equivalent to

int count;
int x;
int *intptr;

Optionally, you can add an initializer to each declarator or to some fo them. So

int count = 10, x, *intptr;

is the same as

int count = 10;
int x;
int *intptr;

That's all there's to it.

AndreyT
A: 

Its like

int count, x;

except that count is being initilized to 10

fupsduck
+1  A: 

This is a common source of errors for both novice and expert C (and C++) programmers, together with comma operator. Usual confusion:

int* p, pp;
pp = malloc( sizeof( int ) * N ); /* oops pp is just int, not a pointer */
...
int x;
x = 12, 13, 14; /* and the value of the x is ... */
Nikolai N Fetissov
And the answer is... 14.
Software Monkey