Susano
Susano

Reputation: 284

why I can't declare variables on the fly while making the conditions in the for loop as an example?

I had made this code that iterate through the alphabets using their ascii code

#include <stdio.h>

int main() {
    for ( int alphabet = (int) char A = 'A'; alphabet <= (int) char Z = 'Z'; alphabet++) {
        printf("The number of the Alphabet %c is %d\n ",(char) alphabet , alphabet  );
    }
}

but upon compiling it just say that it is expected to have an expression before char A or char B which I don't really understand what does that mean so any help will be appreciated xD

Upvotes: 0

Views: 64

Answers (1)

Rohan Bari
Rohan Bari

Reputation: 7726

You don't need to define identifiers like (int) char A = 'A' to represent characters.

Just simply do:

for (int alphabet = 'A'; alphabet <= 'Z'; alphabet++)
    printf("The number of the Alphabet %c is %d\n", alphabet, alphabet);

Notice that you don't need to use (char) in the printf(), it automatically converts into the character from the integer. Also, you don't need to use curly-braces for single syntax in loops & conditions, it's recommended to do to avoid confusions their ending scopes.

Upvotes: 2

Related Questions