Reputation: 145
What is going wrong with my switch function? it looks like this
void ss(int argc, char *argv[])
{
int side_length = 200;
double red = 0.0;
double green = 0.0;
double blue = 0.0;
for (int i = 1; i <= argc; i++) {
printf("%s\n", argv[i]);
if (*argv[i] == '-'){
switch (*++argv[i]) {
case 'r':
red = sin(0.2*atof(argv[i++]));
printf("argv: %f\n", sin(0.2*atof(argv[i++])));
printf("red: %f\n", red);
break;
}
}
}
}
I'm planning to add more switch cases later, but right now I'm focusing on red so I can just replicate it. It seems like the problem is in that it just doesn't store the value I want it to in red, it returns the value in the other printf statement just fine.
edit: I have since used both for (int i = 1; i < argc; i++) and for (int i = 1; argv[i] != '\0'; i++) and neither have worked. Still looking for an answer.
Upvotes: 0
Views: 79
Reputation: 223872
You're trying to do too much at once with the increment operator. As a result, you get confused as to what the code is doing. Specifically, you increment i
twice inside of the loop when calculating the sine.
Break out the extra increment only when it's needed:
for (int i = 1; i < argc; i++) {
printf("%s\n", argv[i]);
if (argv[i][0] == '-'){ // check the first char of the current arg
switch (argv[i][1]) { // check the second char of the current arg
case 'r':
red = sin(0.2*atof(argv[i+1])); // grab the value from the next arg
printf("argv: %f\n", sin(0.2*atof(argv[i+1]))); // grab the next arg again
printf("red: %f\n", red);
i++; // do an extra increment at the end since we processed 2 args
break;
}
}
}
Upvotes: 1
Reputation: 41625
Because of the too many i++
operations, your program invokes undefined behavior, since you access the argv
array out of bounds.
After that, you cannot say anything about the program's behavior. It is even allowed to delete all your files.
Upvotes: 0