Learning C: is this valid?
Author |
Message |
da_foz
|
Posted: Mon Jul 25, 2005 2:34 pm Post subject: Learning C: is this valid? |
|
|
code: |
main(argc, argv)
int argc;
char **argv; {
int i;
for( i=1; i < argc; i++ )
}
|
Got this from http://www.lysator.liu.se/c/bwk-tutor.html#pointers (part 18 ).
I don't understand the brackets around the for loop. I'm not sure if they left something out that I am supposed to infer or what is happening. The part of the lesses is supposed to be an introduction to the command line arguments (argc, argv).
I don't get it. I am coming from a Java background and am currently working in PHP.
EDIT: this one I understand what its supposed to do, just not how it does it.
code: |
main(argc, argv)
int argc;
char **argv; {
...
aflag = bflag = cflag = 0;
if( argc > 1 && argv[1][0] == '-' ) {
for( i=1; (c=argv[1][i]) != '\0'; i++ )
if( c=='a' )
aflag++;
else if( c=='b' )
bflag++;
else if( c=='c' )
cflag++;
else
printf("%c?\n", c);
--argc;
++argv;
}
...
|
I nderstand what --argc; ++argv; are supposed to do, but not how they do it from where they are. The curly brackets make no sense to me. I see the ones for the if, but for about the for? |
|
|
|
|
|
Sponsor Sponsor
|
|
|
wtd
|
Posted: Mon Jul 25, 2005 3:22 pm Post subject: (No subject) |
|
|
That's very old form C. Stop reading whatever tutorial you're reading that still uses that syntax.
c: | int main(int argc, char **argv)
{
int i;
for (i = 1; i < argc; i++)
} |
This is not valid code, but I'll tell you what the various things inside the parens for the for loop are doing.
The first part is setting up the initial state. "i" is zero.
The second part is testing to see that "i" is less than "argc". "argc" holds the number of arguments submitted to the program at the command-line. Those arguments are pointed to by argv.
The third part increments "i" so we can access the next argument in argv.
"i" is a very poor variable name.
c: | int main(int argc, char **argv)
{
int argumentIndex;
for (argumentIndex = 1; argumentIndex < argc; argumentIndex++)
} |
Better.
In the end, what you need to realize is that this is a very poor tutorial, but even with a good tutorial, C is a very poor choice for programmers without a good deal of experience in other languages. |
|
|
|
|
|
|
|