Point Out The Error Series 1

Point out the error in the programs. We are discussing the program, its output and explanation.


1) Program

Our 30-40% of community members thinks error in the program because we are assigning multiple values to one variable. Nothing wrong in this.

We can write

int a;
a = 1,2,3;

Above code is valid code.

In this case, 1 value will assign to a. To know why

Now, check the following program carefully

int main()
{
    int a=1, b, c;
}

In above code, a, b, c three variables are created.

value 1 will assign to a and b,c will get some garbage value.

Below code is similar to above code,

int main()
{
    int a=1, 2, 3;
}

Here 2 and 3 are not valid identifiers . Check this post for naming a variable.

That’s why we got a error

 error: expected identifier or ‘(’ before numeric constant
           int a=1,2,3;
                   ^

Because 2 is not a valid variable name, variable name must start with letter or underscore.


If you have any doubts, let me know in the comment section .


2) Program

New C Programming question, point out error in the program #2.

First of all, let me clear the one thing.

#include<stdio.h>
int fun()
{
    return 1;
}
int main()
{
    int a = fun();
    printf("%d",a);
    return 0;
}

The output of above code is 1, because we called function fun(). fun() returns 1 and value 1 is now assigned to variable a .

Now check this code.

#include<stdio.h>
int fun()
{
    return 1;
}
int main()
{
    printf("%d",fun());
    return 0;
}

Here instead of storing the value returning from function fun() into variable a. We directly print it. So the output of above code is also 1.


Now consider the following code.

#include<stdio.h>

int main()
{
    int a = 1;
    int b = 2;
    int a = 3;    //we can't declare a variable twice in a block
    
    return 0;
}

We can not declare a variable more than once in a block.

#include<stdio.h>
int fun(int a)        // a is declared here
{
    int a = 2;        // we are trying to declare and define variable a twice. And this is invalid
    return a;
}
int main()
{
    printf("%d",fun(1));
    return 0;
}

That’s why the error in the given program is we can not declare variable a twice in a single block i.e. in fun() block.

The error is ( I have used online compiler)


jdoodle.c: In function ‘fun’:
jdoodle.c:4:9: error: ‘a’ redeclared as different kind of symbol
    4 |     int a = 2;        // we are trying to declare and define variable a twice. And this is invalid
      |         ^
jdoodle.c:2:13: note: previous definition of ‘a’ was here
    2 | int fun(int a)        // a is declared here
      |         ~~~~^

If you have any doubt feel free to mention your doubts in comment section below and if you gain some knowledge then also mention what you gain from this post .

Thank You….



CsCode

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top