#include<stdio.h>
int main() {
int A=1,B=4,C=3,D=3;
int res1=A-B;
int res2=B-D;
if(res1<0){
int res1=(-1)*res1;
if(res1>=res2){
printf("%d\n",res1);
}
}
}
I want the res1 as an absolute value(eg:-5 will be assigned as 5) but when execute the code there output terminal is blank. Please reply me want is wrong with my logic.
The if block introduces inner scope and declaration of res1 in the inner scope will hide the res1 declared and defined in the outer scope. Within the if block wherever you use res1, it will be the res1 declared in inner scope and not the one in the outer scope.
Also, in this statement of if block,
int res1=(-1)*res1;
the uninitialised res1 is used in the expression used to initialise it. In the context of your program, this is undefined behaviour (curious to know why!, check this and this).
To fix the problem, either follow the suggestion given in the comment i.e. don't redeclare the res1 in if block or you can also use standard library function abs() to get the absolute value of res1:
if ((res1 < 0) && (abs(res1) >= res2)) {
printf("%d\n", abs(res1)); //assuming you want to print absolute value of res1
}
Note that, to use standard library function abs(), stdlib.h header file need to include in the program.
Related
This is my code:
#include <stdlib.h>
#include <stdio.h>
int sum(int,int);
int sum(int x, int size) {
int sum = 0;
printf("%p\n", &x);
printf("%p\n", &size);
printf("%p\n", &sum);
sum(x,size);
return 0;
}
int main() {
sum(2,4);
return 0;
}
And the error I am getting is:
hello.c:11:5: error: called object type 'int' is not a function or function pointer
sum(x,size);
~~~^
You changed the meaning of sum here:
int sum = 0;
From now on, in the scope in which it was declared, sum is an int, and this becomes nonsense:
sum(x,size); /* Wat? sum is an int!!! */
Don't do that, and your code will compile. Once it compiles, you can worry about stopping the recursion.
If you define two separate identifiers of same name for different entities in the same name space, they might overlap. C11 standard, chapter §6.2.1 states,
If an identifier designates two different entities in the same name
space, the scopes might overlap....
Refer Footnote: Why in this scenario, both sums are in same name space
So, once you re-define the identifier with some other type,
....If so, the scope of one entity (the inner scope) will end
strictly before the scope of the other entity (the outer scope). Within the inner scope, the identifier designates the entity declared in the inner scope; the entity declared in the outer scope is hidden (and not visible) within the inner scope.
That means, essentially, in your case, inside function sum(), when you're defining int sum, basically you're shadowing the function sum. After the re-definition, sum is an identifier of type int, in that function scope. Thus, inside the function sum(), you cannot make a call to sum() as that is an int type now.
However, FWIW, the call to sum() in main() (or, rather, outside sum() itself) should be valid, as at that point, int sum will be out of scope.
Solution: Change the int sum variable name to something else.
Thanks to #pmg for the correction
EDIT:
As mentioned in the other answer by #juanchopanza, after changing the shadowing variable name, your program will compile and once you run it, you'll face infinite recursion due to the unconditional call to sum() inside sum() itself. You need to add some break condition to end (return from) the recursion.
FootNote:
Referring to C11, chapter §6.2.3, name spaces, we can say, there are separate name spaces for various categories of identifiers, e.g. 1) label names 2) the tags of structures, unions, and enumerations, 3) the members of structures or unions and 4) all other identifiers.
So, in this particular case, the function sum() and the int sum definition will reside in the same name space, for the sum() function scope
The scope matters
Function name sum here has a global scope.
Variable sum is local and has local scope.
The conflict is because inside sum() you call sum(). Now inside function sum() you have 2 objects of same name and of different type hence the error.
If you had something like
int sum()
{
int sum = 0;
sum = 10;
printf("%d\n",sum);
}
Then your code would have been fine. Since variable sum is local to function sum() and it is the only object within function sum() with that name.
Instead of worrying about this better to rename the variable and make sure variable name and function name is different
You need to change int sum = 0 to int y = 0, also your program will break as you dont stop recursion at sum(x,sum)
Simply change variable sum name inside sum function to total
#include <stdlib.h>
#include <stdio.h>
int sum(int,int);
int sum(int x, int size) {
int total = 0;
printf("%p\n", &x);
printf("%p\n", &size);
printf("%p\n", &total);
sum(x,size);
return 0;
}
int main() {
sum(2,4);
return 0;
}
Variable and function is of same name thats why it is de-referencing function and variable same time thats the cause of error
I unknowingly named a variable twice but with different data type. It missed the compilation error as one is in main() and other is in while() loop of main().
So I made a code like this.
#include <stdio.h>
int main()
{
int t;
scanf("%d",&t);
while(t>0)
{
double t;
scanf("%lf",&t);
printf("%lf\n",t);
t--;
}
return 0;
}
And here I notice that the program never ends! For any input value of double t either a negative or positive or zero, while() loop never gets terminated.
Can anyone care to explain why is this happening? How does the while loop get terminated there?
You said it yourself. You have two variables named t with different scope.
The double t you declared has the scope of the block that executes inside of the while loop. The conditional in the while loop uses the t that is declared in the scope surrounding the while loop (the int t) which is never modified (because the loop hides t and modifies the double t) and so it never reaches 0.
Here are some points about scope of variables in C:
blocks inherit all global variables
variables declared inside a block are only valid inside the block
blocks can be nested
a nested block inherits the variables from the outer block,
variables may be declared in a nested block to hide variables in the outer block (such as in your case)
EDIT
As #pmg suggested, here are a couple of extra points:
a hidden variable cannot be accessed at all, except through use of pointers created when it was still visible
although strictly speaking, hiding variables is not an error, it's almost never a good thing and most compilers will issue warnings when a variable is hidden!
Can anyone care to explain why is this happening?
There are two variables in your program called t. One is an int, at the scope of main, and one is a double, in the scope of the while loop. Inside the while loop the double t is hiding the int t, and your scanf is setting the double t.
How does the while loop get terminated there?
The program can't be terminated from inside the while loop as written.
while(t>0)//int t;
{
{
double t;
scanf("%lf",&t);
printf("%lf\n",t);
}
t--;
}
When the statement t-- is executed, it refers to the (double t) variable declared earlier in the same block, so your int t in the outer block scope, which is shadowed by the double t, never gets decremented.
An 80k reputation contributor R.. told me on SO that we can't initialize global variables with the return value of a function as that's not considered a constant,and global variables must be initialized with a constant.And true to his words,I get the following error for this program as expected-- initializer element is not a constant.Here is the program:
#include<stdio.h>
int foo();
int gvar=foo(); //ERROR
int main()
{
printf("%d",gvar);
}
int foo()
{
return 8;
}
But in this context,I just don't understand why the followed altered version of the above program shows no error at all and works fine.In this second program,I am initializing the same global variable with the return value of the same function foo().Can you tell me what is the rigorous technical reason for this variation in results?Why is initializing the global variable with the return value of a function at it's declaration causing error but the same initialization with the same return value works fine when done from within a function?
#include<stdio.h>
int foo();
int gvar;
int main()
{
gvar=foo();
printf("%d",gvar);
}
int foo()
{
return 8;
}
Output 8
The reason behind it is that in order to determine a value produced by a function one needs to execute code, and that there is no code execution done in C when initializing static and global variables.
Compiler and linker work together to prepare a byte image of the global memory segment: the compiler provides the values, and the linker performs their final layout. At runtime, the image of the segment is loaded in memory as is, without further modifications. This happens before any code gets executed, so no function calls can be made.
Note that this does not mean that it is not possible for some technical reason, only that C designers decided against doing it. For example, C++ compiler generates a code segment that calls constructors of global objects, which gets executed before the control is passed to main().
The second version doesn't have an initializer for gvar. gvar is declared and defined at global scope without an initializer. It has static storage duration, so it is initialized with zero.
The assignment in main is just that: an assignment, not an initialization.
In case 1, global variable is assigned with a variable while it is declared.
But in the second case, global variable is assigned(which is already declared) with return value of foo().
Forming of data section, text section all happens during compilation.
Global variables will be in data section(bss or initialized data section), so at compile time, foo() is not invoked right? and return value of foo() is not known during compilation.
But second case, when the text section get executed, gvar is assigned with return value of foo(). It is valid.
You can maybe think of it like this: when main() starts, all global variables must already have their initializer values. And they can't, as you've been told, get those by calling functions since main() is really where execution starts, in a C program.
we could not call any function from outer of the function.Not like shell script.function only allow to called from inside of function body.
In c first execution begins from main(), compiler don't know the function calling if that stands on outer of function it may taken as prototype if arg and return types provided.
we can putting return value of function by calling from main or others function block, to the variable,the function called then (that global) variable modified.
but we can use macro in global variable as needs.
as:
#define max() 12
int glob=max();
main()
{
}
Is there a specific term for the following type of C code? In my example, I want to increase the depth of scope for a small chunk of code within a function without having to use needless if/else/for statements so that I can re-declare a variable with the same name multiple times. eg:
void myfunc(void) {
int a = 0, b = 1;
{
int c;
c = 3;
printf("c is: %d", c);
}
a = 2;
{
int c = 5;
printf("c is %d", c);
}
}
What is the term used to describe how I just wrapped some code in curly braces and increased the scope depth so the rest of the function doesn't see the 'c' int?
Thanks!
Scope is defined as the area in which the object is active. There are five scopes in C. They are as follows.
Program Scope
These are the declarations at the top most layers. They are available up to the life of a program. All the functions have this scope. This is otherwise known as global scope.
File Scope
It has scope such that it may be accessed from that point to the end of the file.
void dummy(void) { }
// absence of static automatically gives program scope to `dummy()`
static void dummy(void) { }
// static keyword here gives function `dummy()` a file scope
Function Scope
Only labels have this scope. In this scope, they are active up to end of the function.
void printFun()
{
print:
printf(“i is less than j”);
}
int main()
{
int i=1,j=2;
if(i < j)
goto print;
}
This code will be flagged error by the compiler saying that the label print is not known because labels have only function scope. If you have to jump unconditionally between the functions, you have to use setjmp/longjmp functions.
Block Scope
Declarations that are active up to the end of the block (where a block is defined as statements within { }). All the declarations inside the function have only block scope.
int fun(int a, int b)
{
int c;
{
int d;
}
// a, b, c, d all have block scope
}
As I have said, function scope applies only to labels. So should not be confused with block scope. The function arguments are treated as if they were declared at the beginning of the block with other variables (remember that the function body is also considered as a block within { }). So the function arguments have block scope (not function scope).
Local scope is general usage to refer the scope that is either function or block scope.
Prototype Scope
They are having the scope only inside the prototype declaration. This scope is interesting because the variable names are valid only in the declaration of prototype and does not conflict with other variable names. It exists for very little time and of less use and so goes unnoticed.
int add(int a, float b);
Here the variables a and b are said to have prototype scope.
Selecting Minimal Scope
When a name has to be resolved, that name is searched in the minimal scope, and if that is not available, it is searched at higher levels of scope. So, if a variable has to be declared, you have to select a minimal scope possible. If you can limit your scope, that increases the efficiency, readability and maintainability of your program. If you want a variable which is not useful outside a block, declare it inside the block and not in the outer ones. Similarly, if you want a variable whose value will be accessed only within the function but has to retain the value between the function calls, opt for static variable to a global one.
I'd say you are introducing a new local scope, or a nested scope, or a block.
This becomes seriously important in C++ when you take active advantage of this:
{
std::lock_guard<std::mutex> lk(my_mutex);
do_critical_stuff(); // might throw exception?
}
// the lock is released automagically!
But even in C it's good practice to only use variables locally where they're needed and not bleed them into unnecessarily wide scopes.
The term is the scope.
K&R2 defines the word scope as
A name also has a scope, which is the region of the program in which
it is known
Scope is the word that refers to the visibility of an identifier.
I've come across a bit of code that contains a couple code blocks, delineated with curly braces {}. There is no line before the code blocks marking them as part of if statements, function definitions, or anything else. Just a code block floating in the middle of a function. Is there any meaning to this? gcc seems perfectly happy going through the code; I can only imagine it is some way to allow the original coder to split up blocks of functionality visually...
It creates a scope. Are there automatic variables defined inside the blocks? If so, then the scope of those variables is confined to the block. It's useful for temporary variables that you don't want polluting the rest of the function, and it's also useful when writing C89, where variable definitions must be at the start of a block.
So, instead of:
int main() {
int a = 0;
int b;
int i;
for (i = 1; i < 10; ++i) {
a += i;
}
b = a * a;
// do something with a and b
}
You could have:
int main() {
int a = 0;
{
int i;
for (i = 1; i < 10; ++i) {
a += i;
}
}
{
int b = a * a;
// do something with a and b
}
}
Obviously if you're doing this, you also have to ask yourself if the blocks wouldn't be better off as separate functions.
Standalone curly braces are used for scoping—any variables declared in a block aren't visible outside it.
If the code blocks contain local variable declarations (your description is not clear about what's inside), they may be there to limit the scope of those variables. I.e.
int i = ...;
// i is visible here
{
int j = ...;
// both i and j are visible here
}
// j went out of scope, only i is visible here
It is used to create a scope. A scope if useful to declare variables that can only be used inside this scope. For example, if a variable is declared before the braces, it can be used inside the braces of after them. At the contrary, if a variable is declared inside the braces, it can only be used inside the braces.
Hope this helps.
It usually means it was written to declare a variable part way through a larger function, but the variable only needs a very limited scope, or may even need to hide something. It is entirely legimitate - it simply introduces a block. The big issue is always "what is the correct indentation for that code".
It can also be used by pre-processors that convert some other language into generated C. The converted material is often wrapped in a block (and possibly #line directives too).