Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple type specifiers in declaration list

#include <cs50.h>
#include <stdio.h>
#include <string.h>

int main(void)
{
    //ask user for input
    string s = get_string();

    //make sure get_string() returned a string
    if(s != NULL)
    {
        //iterate over the characters one at a time
        for(int i = 0, int n = strlen(s); i < n; i++)
        {
            //print i'th character in s
            printf("%c\n", s[i]);
        }
    }
    else
    {
        //tell the user that their input is not a string
        printf("Sorry, no good\n");
    }

}

The compiler complained about this line:

for(int i = 0, int n = strlen(s); i < n; i++)

because I declared the integer n with int to define the type.

The program compiles just fine with:

for(int i = 0, n = strlen(s); i < n; i++)

Why is int required/good form for i, but not for n in this example?

like image 983
phindex Avatar asked Dec 08 '22 16:12

phindex


1 Answers

It's because this line:

int i = 0, n = strlen(s)

creates two integers called i and n and initialises them.

When you put:

int i = 0, int n = strlen(s)

You create an int called i and initialise it, and then you attempt to create another int called int n which doesn't make sense.

There's no reason to initialise n where it is - it shouldn't change, after all. Initialise it before the loop:

int n = strlen(s); 

for(int i = 0; i < n; i++)
{
    ...
like image 162
Steve Avatar answered Dec 26 '22 23:12

Steve